Home > other >  Odd timezone behaviour in python (pytz)
Odd timezone behaviour in python (pytz)

Time:11-27

I'm encountering a strange issue with timezones in python that I've boiled down to a few lines of code:

from datetime import time, datetime
import pytz
tz = pytz.timezone('Canada/Pacific')
d = datetime.now(tz=tz)
t = time(tzinfo=tz)

When inspecting the tzinfo objects in d and t, the one in t gives a timezone with a utc-offset of 8:12, while the one in d gives a utc-offset of just 8 hours, which is the correct offset. The tz instance also gives a utc-offset of 8:12. What's with the extra 12 minutes?

I realize that datetime.now() is dependent on when you run the code, so I will say that I ran it a few minutes before posting this on StackOverflow and saw the same error. Can someone more knowledgable on timezones help me figure out what the problem is?

CodePudding user response:

@Ruli the answer is just to read the documentation.

tz = pytz.timezone('Canada/Pacific')
dt = tz.normalize(datetime.now())
t = tz.normalize(time())

is the correct way of creating local times.

CodePudding user response:

For posterity, the issue is that we can't actually use pytz.timezone() and provide that to the tzinfo parameter.

  • Related