I want to print the current time in ISO 8601 format as close as possible to Python's isoformat() function, which produces output like 2024-01-16T09:32:46.090+01:00.
As a starting point, I have this code that uses gettimeofday(), localtime(), and strftime():
#include <stdio.h> //printf
#include <sys/time.h>
int main(){
struct timeval tv;
struct timezone tz;
gettimeofday(&tv, &tz);
char buf[30]; // 29 chars + '\0'
strftime(buf, 30, "%Y-%m-%dT%H:%M:%S%z", localtime(&tv.tv_sec));
printf("using strftime: %s\n", buf);
}
That generates 2024-01-16T09:32:46+01:00 (missing milliseconds).
I didn't not find any format specifier for strftime() to print milliseconds.
strftime()takes astruct tmas input, andstruct tmhas no notion of milliseconds/microseconds sostrftime()can't get milliseconds out of it.In order to the the milliseconds you will need to resort to the
struct timevalreturned bygettimeofday()which has a member calledtv_usecwith the microseconds that you can easily convert to milliseconds by dividing by 1000. Or useclock_gettime()which provides nanoseconds. See an example withclock_gettimeat the bottom.When executed it will produce
2024-01-16T14:08:15.079+0100which matches ISO 8601 with milliseconds and UTC offset. Unfortunately the%zproduces a UTC offset in the form+0100(no colon) instead of+01:00If you really really need the UTC offset with colon, then you can use
struct timezonefromgettimeofday(). You need to replace theoff += strftime(buf+off, 30-off, "%z", local);to more convoluted:Note that
gettimeofday()is considered deprecated in favor ofclock_gettime(), so the best way to do all this would be:The only changes are to use
clock_gettime()instead ofgettimeofday()and use the time zone information thatlocaltime()provides in thestruct tmastm_gmtoff.