英文:
How to print print timestamp in format [2023-07-05 15:00:07.680973] inside C code
问题
如何以格式 [2023-07-05 15:00:07.680973] 打印时间戳?
英文:
How to print timestamp in format [2023-07-05 15:00:07.680973]?
答案1
得分: 1
以下是打印带微秒的本地时间的一种方法:
#include <stdio.h>
#include <time.h>
int main(void) {
struct timespec ts;
// 修改由ts指向的timespec对象,以包含基于TIME_UTC的当前日历时间:
timespec_get(&ts, TIME_UTC);
// 将自纪元以来的给定时间(一个time_t值)转换为本地时间中的日历时间,以struct tm格式表示:
struct tm lt = *localtime(&ts.tv_sec);
char buff[100];
// 将来自日历时间“lt”的日期和时间信息转换为字符串:
strftime(buff, sizeof buff, "%F %T", <);
printf("[%s.%06ld]\n", buff, ts.tv_nsec/1000);
}
阅读:
英文:
Here's one way to print the local time with microseconds:
#include <stdio.h>
#include <time.h>
int main(void) {
struct timespec ts;
// Modify the timespec object pointed to by ts to hold the current
// calendar time in the time base TIME_UTC:
timespec_get(&ts, TIME_UTC);
// Convert given time since epoch (a time_t value) into calendar time, expressed
// in local time, in the struct tm format:
struct tm lt = *localtime(&ts.tv_sec);
char buff[100];
// Convert the date and time information from a the calendar time `lt` to a string:
strftime(buff, sizeof buff, "%F %T", &lt);
printf("[%s.%06ld]\n", buff, ts.tv_nsec/1000);
}
Read:
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论