【发布时间】:2014-01-17 13:31:48
【问题描述】:
我正在尝试使用 strptime 将字符串解析为 struct tm。看起来很简单,但它没有正确填写年份(是的,我知道 1900 偏移量) - 通话后,年份设置为 0。其他字段看起来没问题。见下文:
struct tm tm;
memset(&tm, 0, sizeof(struct tm));
strptime("Fri Jan 17 09:44:33 UTC 2014", "%a %b %d %H:%M:%S %Z %Y", &tm);
在 strptime 调用之后,tm 结构如下 - 请注意 tm_year=0,我预计它是 114:
{tm_sec = 33, tm_min = 44, tm_hour = 9, tm_mday = 17, tm_mon = 0, tm_year = 0,
tm_wday = 5, tm_yday = 0, tm_isdst = 0, tm_gmtoff = 0, tm_zone = 0x0}
我确定我遗漏了一些简单的东西 - 有人能指出来吗?
【问题讨论】:
-
我猜它会尝试匹配 %Z 中的整个字符串
-
它可以在 Python 中工作,但不能在 C++ 中工作:
>>> datetime.datetime.strptime("Fri Jan 17 09:44:33 UTC 2014", "%a %b %d %H:%M:%S %Z %Y") datetime.datetime(2014, 1, 17, 9, 44, 33) -
是的,就是这样。如果我删除 %Z 并使用以下格式字符串,我会正确获得年份:“%a %b %d %H:%M:%S UTC %Y”。由于我知道所有时间都将在 UTC 中,因此我可以侥幸逃脱,尽管并不优雅。我可能会尝试 sscanf 方法...
-
我一直认为这种日期时间格式非常愚蠢。
-
天哪,谁会选择这种可怕的格式?