0
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?

jfs
  • 399,953
  • 195
  • 994
  • 1,670
math4tots
  • 8,540
  • 14
  • 58
  • 95
  • Use `localize`, not `replace`. Read [the pytz docs](http://pythonhosted.org/pytz). – Matt Johnson-Pint Apr 03 '15 at 21:00
  • @MattJohnson: `.now(tz)` works as is. You shouldn't use `tz.localize(.now())` here even if the local timezone is `'US/Pacific'` (the latter fails during end-of-DST transitions while the former works without an issue even for ambiguous local times). – jfs Apr 03 '15 at 21:08
  • @J.F.Sebastian - Yes, agreed for the case of "now". I was speaking in general. Thanks. – Matt Johnson-Pint Apr 03 '15 at 22:26

1 Answers1

2

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.

Community
  • 1
  • 1
jfs
  • 399,953
  • 195
  • 994
  • 1,670