math4tots
math4tots

Reputation: 8869

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?

Upvotes: 0

Views: 37

Answers (1)

jfs
jfs

Reputation: 414895

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.

Upvotes: 2

Related Questions