Web log timestamp to Unix epoch with strptime

This code turns an Apache web log time stamp of the form [31/May/2006:23:59:38 -0700] into a Unix epoch-based time (like the return value from time) using the strptime function.

#include <stdio.h>
#include <time.h>

time_t extract_timestamp (const char * timestamp_string)
{
    struct tm timestamp_tm;
    const char * sresult;
    time_t tresult;

    sresult = strptime (timestamp_string, "[%d/%b/%Y:%T %z]", & timestamp_tm);
    if (sresult == 0) {
        fprintf (stderr, "strptime failed for %s\n", timestamp_string);
        exit (1);
    }
    /* Use timelocal here because strptime ignores the timezone and
       interprets the string as local time. This is a case of two
       wrongs making a right. */
    tresult = timelocal (& timestamp_tm);
    return tresult;
}

int main ()
{
    time_t t = extract_timestamp ("[31/May/2006:23:59:38 -0700]");
    printf ("%X\n", t);
    return 0;
}

Copyright © Ben Bullock 2009-2023. All rights reserved. For comments, questions, and corrections, please email Ben Bullock (benkasminbullock@gmail.com) or use the discussion group at Google Groups. / Privacy / Disclaimer