python datetime 时间戳转换不一致
python datetime timestamp conversion inconsistency
当我尝试将日期时间对象转换为时间戳并将其转换回结果时,如果关闭 53 分钟。
timestamp = datetime.datetime(2022, 5, 3, 18, 0, 0, 0, tzinfo=pytz.timezone('US/Pacific')).timestamp()
# timetamp = 1651629180
datetime.datetime.fromtimestamp(timestamp, tz=pytz.timezone('US/Pacific'))
# formmated_timestamp = datetime.datetime(2022, 5, 3, 18, 53, tzinfo=<DstTzInfo 'US/Pacific' PDT-1 day, 17:00:00 DST>)
结果不知何故偏离了 53 分钟。对于所有其他值也是如此
问题似乎在 .timestamp()
部分
来自pytz docs:
This library only supports two ways of building a localized time. The first is to use the localize()
method provided by the pytz library. This is used to localize a naive datetime (datetime with no timezone information):
>>> loc_dt = eastern.localize(datetime(2002, 10, 27, 6, 0, 0))
>>> print(loc_dt.strftime(fmt))
2002-10-27 06:00:00 EST-0500
The second way of building a localized time is by converting an existing localized time using the standard astimezone()
method:
>>> ams_dt = loc_dt.astimezone(amsterdam)
>>> ams_dt.strftime(fmt)
'2002-10-27 12:00:00 CET+0100'
Unfortunately using the tzinfo argument of the standard datetime constructors ''does not work'' with pytz for many timezones.
>>> datetime(2002, 10, 27, 12, 0, 0, tzinfo=amsterdam).strftime(fmt)
'2002-10-27 12:00:00 LMT+0020'
当我尝试将日期时间对象转换为时间戳并将其转换回结果时,如果关闭 53 分钟。
timestamp = datetime.datetime(2022, 5, 3, 18, 0, 0, 0, tzinfo=pytz.timezone('US/Pacific')).timestamp()
# timetamp = 1651629180
datetime.datetime.fromtimestamp(timestamp, tz=pytz.timezone('US/Pacific'))
# formmated_timestamp = datetime.datetime(2022, 5, 3, 18, 53, tzinfo=<DstTzInfo 'US/Pacific' PDT-1 day, 17:00:00 DST>)
结果不知何故偏离了 53 分钟。对于所有其他值也是如此
问题似乎在 .timestamp()
部分
来自pytz docs:
This library only supports two ways of building a localized time. The first is to use the
localize()
method provided by the pytz library. This is used to localize a naive datetime (datetime with no timezone information):>>> loc_dt = eastern.localize(datetime(2002, 10, 27, 6, 0, 0)) >>> print(loc_dt.strftime(fmt)) 2002-10-27 06:00:00 EST-0500
The second way of building a localized time is by converting an existing localized time using the standard
astimezone()
method:>>> ams_dt = loc_dt.astimezone(amsterdam) >>> ams_dt.strftime(fmt) '2002-10-27 12:00:00 CET+0100'
Unfortunately using the tzinfo argument of the standard datetime constructors ''does not work'' with pytz for many timezones.
>>> datetime(2002, 10, 27, 12, 0, 0, tzinfo=amsterdam).strftime(fmt) '2002-10-27 12:00:00 LMT+0020'