Python datetime difference between .localize and tzinfo

泄露秘密 提交于 2020-01-03 15:20:34

问题


Why do these two lines produce different results?

>>> import pytz
>>> from datetime ipmort datetime

>>> local_tz = pytz.timezone("America/Los_Angeles")

>>> d1 = local_tz.localize(datetime(2015, 8, 1, 0, 0, 0, 0)) # line 1
>>> d2 = datetime(2015, 8, 1, 0, 0, 0, 0, local_tz) # line 2
>>> d1 == d2
False

What's the reason for the difference, and which should I use to localize a datetime?


回答1:


When you create d2=datetime(2015, 8, 1, 0, 0, 0, 0, local_tz) in this way. It does not handle daylight savings time correctly. But, local_tz.localize() does.

d1 is

datetime.datetime(2015, 8, 1, 0, 0, 
                  tzinfo=<DstTzInfo 'America/Los_Angeles' PDT-1 day, 17:00:00 DST>)

d2 is

datetime.datetime(2015, 8, 1, 0, 0, 
                  tzinfo=<DstTzInfo 'America/Los_Angeles' PST-1 day, 16:00:00 STD>)

You can see that they are not representing the same time.

d2 way it's fine if you are gonna work with UTC. Because UTC does not have daylight savings time transitions to deal with.

So, the correct way to handle timezone, it's using local_tz.localize()



来源:https://stackoverflow.com/questions/39460236/python-datetime-difference-between-localize-and-tzinfo

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