Why does datetime give different timezone formats for the same timezone?

你说的曾经没有我的故事 提交于 2021-02-08 13:58:11

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!