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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3694487/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 12:17:02  来源:igfitidea点击:

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

pythondatetimedatetimeepoch

提问by Adam Matan

The timemodule can be initialized using seconds since epoch:

time模块可以使用自纪元以来的秒数进行初始化:

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

Is there an elegant way to initialize a datetime.datetimeobject in the same way?

有没有一种优雅的方式以datetime.datetime同样的方式初始化一个对象?

采纳答案by SilentGhost

datetime.datetime.fromtimestampwill do, if you know the time zone, you could produce the same output as with time.gmtime

datetime.datetime.fromtimestamp会做,如果你知道时区,你可以产生与 time.gmtime

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

or

或者

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

回答by Seganku

Seconds since epoch to datetimeto strftime:

从 epoch 到datetimeto 的秒数strftime

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

回答by cbare

Note that datetime.datetime.fromtimestamp(timestamp) and .utcfromtimestamp(timestamp) fail on windows for dates before Jan. 1, 1970 while negative unix timestamps seem to work on unix-based platforms. The docs say this:

注意datetime.datetime。fromtimestamp(时间戳)和 . utcfromtimestamp(timestamp) 在 1970 年 1 月 1 日之前的日期在 windows 上失败,而负的 unix 时间戳似乎在基于 unix 的平台上工作。文档是这样说的:

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

如果时间戳超出平台 C gmtime() 函数支持的值范围,这可能会引发 ValueError。通常将此限制在 1970 年到 2038 年之间

See also Issue1646728

另见Issue1646728

回答by Meistro

From the docs, the recommended way of getting a timezone aware datetime object from seconds since epoch is:

从文档中,从纪元以来的秒数获取时区感知日期时间对象的推荐方法是:

Python 3:

蟒蛇3

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

Python 2, using pytz:

Python 2,使用pytz

from datetime import datetime
import pytz
datetime.fromtimestamp(timestamp, pytz.utc)