ref
https://blog.youkuaiyun.com/GreenTeemo/article/details/102586265
说明
时间戳为2020/03/25 11:09:42 .761197,其中.761197为微秒。
code
#include <stdio.h>
#include <time.h>
#include <sys/time.h>
int main()
{
char time[100] = "2020/03/25 11:09:42 .761197";
char time_format[100] = "%Y/%m/%d %H:%M:%S";
printf("origin is %s\n", time);
/* to tm */
struct tm tm;
strptime(time, time_format, &tm);
printf("tm is %04d-%02d-%02d %02d:%02d:%02d\n", 1900 + tm.tm_year, 1 + tm.tm_mon, tm.tm_mday, tm.tm_hour, tm.tm_min, tm.tm_sec);
/* to time_t */
time_t tt;
tt = mktime(&tm);
printf("time_t is %lu\n", tt);
/* to timeval */
struct timeval tv;
tv.tv_sec = tt;
tv.tv_usec = atoi(time + 21); // 21 = strlen("2020/03/25 11:09:42 .")
printf("timeval is %ld.%06ld\n", tv.tv_sec, tv.tv_usec);
return 0;
}
output
origin is 2020/03/25 11:09:42 .761197
tm is 2020-03-25 11:09:42
time_t is 1585105782
timeval is 1585105782.761197