Timezones in Python weirdness

Check this out:

from datetime import datetime
import pytz

fmt = "%Y-%m-%d %H:%M:%SZ"
timezones = ['US/Pacific','UTC']
date_string = '2017-03-10 13:30:00Z'
t = datetime.strptime(date_string, fmt)
t = t.replace(tzinfo=pytz.timezone('US/Pacific'))
for zone in timezones:
  print zone + ": " + t.astimezone(pytz.timezone(zone)).strftime(fmt)

Nothing special, right? I took a string, made a datetime object out of it, set the timezone to Pacific, and then printed it in a bunch of other timezones. What could possibly go wrong?

US/Pacific: 2017-03-10 13:30:00Z
UTC: 2017-03-10 21:23:00Z

21:23? Where did these seven minutes?
Turns out this is a known issue with pytz that has something to do with daylight saving. I decided to work with a library called “Pendulum” instead. They claim to have better performance too, which doesn’t matter to me at all. This is what the code will look like with Pendulum:

from datetime import datetime
import pendulum

fmt = "%Y-%m-%d %H:%M:%SZ"
timezones = ['US/Pacific','UTC']
date_string = '2017-03-10 13:30:00Z'
t = pendulum.from_format(date_string, fmt, 'US/Pacific')
for zone in timezones:
  timezone = pendulum.timezone(zone)
  print zone + ": " + timezone.convert(t).format(fmt)

Better?

US/Pacific: 2017-03-10 13:30:00Z
UTC: 2017-03-10 21:30:00Z

Better.

Leave a Reply

Your email address will not be published. Required fields are marked *