UTC ISO 8601 日期的时间戳

Timestamp to UTC ISO 8601 date

这个

import datetime
datetime.datetime.fromtimestamp(1501545600).isoformat()

应该输出 2017-08-01T00:00:00Z2017-08-01T00:00:00 但我得到

2017-08-01T02:00:00

相反,可能是因为当地时区。

如何让 .isoformat() 输出 UTC 时间,即 2017-08-01T00:00:00?

如果可能,我只想使用 datetime,而不使用其他第三方库,例如 arrowdateutils

使用 utcfromtimestamp() 而不是 fromtimestamp()。来自 docs:

Return the UTC datetime corresponding to the POSIX timestamp, with tzinfo None.

fromtimestamp() 中没有指定 tzinfo:

If optional argument tz is None or not specified, the timestamp is converted to the platform’s local date and time, and the returned datetime object is naive.

这似乎不是你想要的。

那不应该是datetime.utcfromtimestamp()吗?

来自 python 文档:

classmethod datetime.utcfromtimestamp(timestamp)¶ Return the UTC datetime corresponding to the POSIX timestamp, with tzinfo None. This may raise ValueError, if the timestamp is out of the range of values supported by the platform C gmtime() function. It’s common for this to be restricted to years in 1970 through 2038.