在Python中,如何将自纪元以来的秒数转换为`datetime`对象?

In Python, how do you convert seconds since epoch to a `datetime` object?

time模块可以用epoch以来的秒数初始化:

1
2
3
4
5
>>> import time
>>> t1=time.gmtime(1284286794)
>>> t1
time.struct_time(tm_year=2010, tm_mon=9, tm_mday=12, tm_hour=10, tm_min=19,
                 tm_sec=54, tm_wday=6, tm_yday=255, tm_isdst=0)

是否有一种优雅的方法以同样的方式初始化datetime.datetime对象?


datetime.datetime.fromtimestamp会做,如果你知道时间区,你可以produce相同的输出级与time.gmtime P / < >

1
2
>>> datetime.datetime.fromtimestamp(1284286794)
datetime.datetime(2010, 9, 12, 11, 19, 54)

或 P / < >

1
2
>>> datetime.datetime.utcfromtimestamp(1284286794)
datetime.datetime(2010, 9, 12, 10, 19, 54)


由于时代到datetime秒到strftime: P / < >

1
2
3
4
>>> ts_epoch = 1362301382
>>> ts = datetime.datetime.fromtimestamp(ts_epoch).strftime('%Y-%m-%d %H:%M:%S')
>>> ts
'2013-03-03 01:03:02'


从文档,建议的方式得到的-意识的日期时间对象从秒由于时代: P / < >

Python 3: P / < >

1
2
from datetime import datetime, timezone
datetime.fromtimestamp(timestamp, timezone.utc)

Python的2,用pytz: P / < >

1
2
3
from datetime import datetime
import pytz
datetime.fromtimestamp(timestamp, pytz.utc)


注意,datetime.datetime.fromtimestamp(timestamp)和.utcfromtimestamp(timestamp失败)在Windows dates之前,1月为1。20世纪70年代,而消极的UNIX timestamps似乎工作的C - platforms UNIX为基础的。"文档说: P / < >

"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"

看到也issue1646728 P / < >