how to parse syslog timestamp how to parse syslog timestamp unix unix

how to parse syslog timestamp


The date format is a stricter version of RFC3339 giving a string such as '2011-08-18T23:31:42Z'

I'm not certain the strptime function can deal with the timezone specifier (Z in the time string above), so it may be easier to handle that inside your own function. It definitely can't handle fractional seconds, since struct tm doesn't handle them. You could use struct timespec to store the fractional seconds if required.

You can parse out most of the format using strptime:

struct tm tm;time_t tchar *extra;extra = strptime( tmstr, "%C%y-%m-%dT%H:%M:%S", &tm );tm.tm_isdst = -1;t = mktime( &tm );

Following this, extra will be the remainder of the input tmstr. This could include fractional seconds, and will then contain the timezone format. If extra begins with a '.' just parse the number out with the strtod function:

if( extra && extra[0] == '.' ){  char *endptr;  fraction = strtod( extra, &endptr );  extra = endptr;  /* use timespec if fractional seconds required */  struct timespec ts;  ts.tv_sec = t;  ts.tv_nsec = fraction * 1000000000;}

Then extra will now just contain the timezone specifier. If it is 'Z' then we're done since mktime gives you UTC time anyway. Otherwise you'll have an offset e.g. +03:00, so you will need to modify your time by that number of hours/minutes.