Difference between Python date and time between .localize and tzinfo

Why do these two lines give 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 is the reason for the difference and which should I use to localize datetime?

+4
source share
1 answer

When created d2=datetime(2015, 8, 1, 0, 0, 0, 0, local_tz)this way. He does not cope with summertime. But local_tz.localize()does.

d1 -

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

d2 -

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

You can see that they do not represent the same time.

d2great if you are going to work with UTC. Because UTC does not have daylight saving time to handle.

So, the correct way to process your timezone using local_tz.localize()

+4
source

Source: https://habr.com/ru/post/1654402/


All Articles