问题
>>> 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>)
For now
I got JST+9:00:00 and for dt
I got LMT+9:19:00. I don't understand why datetime
uses a different format.
When I compare the times they are different:
>>> now == dt
False
How can I convert LMT
to JST
so that now == dt
is True
? I need to use datetime(2018, 9, 7, 16, 9, 24, 177751, timezone('Asia/Tokyo'))
and at the same time I want JST
.
回答1:
As noted in a related question's answer, Never create datetime with timezone info by using datetime(). Instead, you should use localize
to convert datetimes to JST after creating them in UTC.
>>> 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
来源:https://stackoverflow.com/questions/52217506/why-does-datetime-give-different-timezone-formats-for-the-same-timezone