我正在编写一些 C 代码,需要将当前时间嵌入到其(二进制)输出文件中。稍后,该文件将被其他一些 C 代码(可能为不同的体系结构编译)和/或一些 python 代码读取。在这两种情况下都可能需要计算时间。
我想知道的是:
- 如何获取 C 语言中的当前 UTC 时间? time() 是写调用吗?
- 我应该以什么格式写入文件? ASN1? ISO?
- 如何转换为该格式?
- 如何用 C 和 Python 读取该格式并将其转换为有用的内容?
最佳答案
您可以使用rfc 3339 datetime format (ISO8601 简介)。它避免了不受约束的 ISO8601 时间戳的许多陷阱。
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main(void) {
char buf[21];
time_t ts = time(NULL);
struct tm *tp = gmtime(&ts);
if (tp == NULL || tp->tm_year > 8099 || tp->tm_year < 0) {
perror("gmtime");
exit(EXIT_FAILURE);
}
if (strftime(buf, sizeof buf, "%Y-%m-%dT%H:%M:%SZ", tp) == 0) {
fprintf(stderr, "strftime returned 0\n");
exit(EXIT_FAILURE);
}
exit(puts(buf) != EOF ? EXIT_SUCCESS : EXIT_FAILURE);
}
输出
2014-12-20T11:08:44Z
用 Python 阅读它:
>>> from datetime import datetime, timezone
>>> dt = datetime.strptime('2014-12-20T11:08:44Z', '%Y-%m-%dT%H:%M:%SZ')
>>> dt = dt.replace(tzinfo=timezone.utc)
>>> print(dt)
2014-12-20 11:08:44+00:00
关于python - 如何在C和Python之间交换时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27545870/