Python Pytz US/Pacific timezone issue

Viewed 4045

Here's my Python code:

import pytz
from datetime import datetime

tz = pytz.timezone('US/Pacific')
now_local = datetime.now().replace(tzinfo=tz)
print("now_local: {}".format(now_local))

It prints this output:

now_local: 2018-11-13 12:06:03.255983-07:53

which is odd because I believe the timezone offset should be -08:00 instead of -07:53. I'm pretty sure that the timezone offset of US Pacific is 8 hours.

Am I missing something?

I'm on Python version 2.7.14 and Pytz version 2018.4

1 Answers

Yes, the homepage of pytz calls out this error:

Unfortunately using the tzinfo argument of the standard datetime constructors “does not work” with pytz for many timezones.

>>> datetime(2002, 10, 27, 12, 0, 0, tzinfo=amsterdam).strftime(fmt)  # /!\ Does not work this way!
'2002-10-27 12:00:00 LMT+0020'

You need to use tz.localize(dt):

>>> print(tz.localize(datetime.now()))
2018-11-13 15:20:12.172381-08:00

Otherwise your tzinfo object is stuck in the "default", which for most zones is some approximation of "Local Mean Time", not any standard time.

Related