>>> 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 == dt
为True
?我需要同时使用datetime(2018, 9, 7, 16, 9, 24, 177751, timezone('Asia/Tokyo'))
和JST
。
答案 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