Search code examples
pythontimezonepytz

Baffling timezone Behavior


import datetime
import pytz # install from pip

US_PACIFIC_TIMEZONE = pytz.timezone("US/Pacific")

dt = datetime.datetime.utcnow().replace(tzinfo=US_PACIFIC_TIMEZONE)
print(dt == dt.replace(tzinfo=US_PACIFIC_TIMEZONE)) # True

dt = datetime.datetime.now(tz=US_PACIFIC_TIMEZONE)
print(dt == dt.replace(tzinfo=US_PACIFIC_TIMEZONE)) # False

So it looks like datetime.datetime.now(tz=..) isn't set to the timezone I specify...

It looks like the timezone is set when using datetime.now, but it's off by an hour-zone.

Why is this?


Solution

  • The only correct formula in your question is:

    dt = datetime.now(US_PACIFIC_TIMEZONE)
    

    US_PACIFIC_TIMEZONE may have different utc offsets at different dates e.g., due to DST transitions. You shouldn't use .replace() method (or tzinfo constructor parameter) with such pytz timezones. Here's an explanation on why you should not use replace() with pytz timezones that have a variable utc offset.