11

Why do these two lines produce different results?

>>> import pytz
>>> from datetime import 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?

GabLeRoux
  • 16,715
  • 16
  • 63
  • 81
Nick
  • 1,864
  • 5
  • 27
  • 49
  • See [this explanation](https://stackoverflow.com/questions/24359540/why-doesnt-pytz-localize-produce-a-datetime-object-with-tzinfo-matching-the-t). – Jerther Jun 12 '18 at 18:03

1 Answers1

8

When you create d2 = datetime(2015, 8, 1, 0, 0, 0, 0, local_tz), it does not handle daylight saving time (DST) correctly. local_tz.localize() does.

d1 is

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

d2 is

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

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

d2 way is fine if you are going to work with UTC. UTC does not have daylight saving time (DST) transitions to deal with.

The correct way to handle timezone is to use local_tz.localize() to support daylight saving time (DST)

More information and additional examples can be found here:
http://pytz.sourceforge.net/#localized-times-and-date-arithmetic

GabLeRoux
  • 16,715
  • 16
  • 63
  • 81
levi
  • 22,001
  • 7
  • 73
  • 74