为什么日期时间为同一时区提供不同的时区格式?

时间:2018-09-07 07:31:18

标签: python python-datetime

>>> now = datetime.datetime.now(pytz.timezone('Asia/Tokyo'))
>>> dt = datetime(now.year, now.month, now.day, now.hour, now.minute, now.second, now.microsecond, pytz.timezone('Asia/Tokyo'))
>>> now
datetime.datetime(2018, 9, 7, 16, 9, 24, 177751, tzinfo=<DstTzInfo 'Asia/Tokyo' JST+9:00:00 STD>)
>>> dt = datetime(now.year, now.month, now.day, now.hour, now.minute, now.second, now.microsecond, pytz.timezone('Asia/Tokyo'))
>>> dt
datetime.datetime(2018, 9, 7, 16, 9, 24, 177751, tzinfo=<DstTzInfo 'Asia/Tokyo' LMT+9:19:00 STD>)

对于now,我得到了 JST + 9:00:00 ;对于dt,我得到了 LMT + 9:19:00 。我不明白为什么datetime使用不同的格式。

当我比较时间不同时:

>>> now == dt
False

如何将LMT转换为JST,使now == dtTrue?我需要同时使用datetime(2018, 9, 7, 16, 9, 24, 177751, timezone('Asia/Tokyo'))JST

1 个答案:

答案 0 :(得分:3)

a related question's answer中所述,永远不要通过使用datetime()来创建带有时区信息的日期时间。相反,在UTC中创建日期时间后,应使用localize将日期时间转换为JST。

>>> import pytz
>>> from datetime import datetime
>>>
>>> now = datetime.now(pytz.utc)
>>> dt = datetime(now.year, now.month, now.day, now.hour, now.minute, now.second, now.microsecond, pytz.utc)
>>> jst = pytz.timezone('Asia/Tokyo')
>>> jst.normalize(now)
datetime.datetime(2018, 9, 7, 20, 21, 44, 653897, tzinfo=<DstTzInfo 'Asia/Tokyo' JST+9:00:00 STD>)
>>> jst.normalize(dt)
datetime.datetime(2018, 9, 7, 20, 21, 44, 653897, tzinfo=<DstTzInfo 'Asia/Tokyo' JST+9:00:00 STD>)
>>> now == dt
True