1

When I run the following code;

tz_Pacific = pytz.timezone('US/Pacific')
tz_Tasmania = pytz.timezone('Australia/Tasmania')

time1 = datetime(2020, 10, 7, 18, 0, 0, tzinfo=tz_Pacific)
time2 = datetime(2020, 10, 7, 14, 20, 21, tzinfo=tz_Tasmania)

print(time1)
print(time2)

I get the following output;

2020-10-07 18:00:00-07:53

2020-10-07 14:20:21+09:49

Why would the tz offsets be -07:53 and +09:49 respectively?

FObersteiner
  • 22,500
  • 8
  • 42
  • 72
  • I note that these are the offsets before the first transition in the IANA database (1883 for US/Pacific and 1895 for Australia/Tasmania). I don't know anything about pytz, but it seems to be ignoring the dates you've provided... – Jon Skeet Oct 07 '20 at 05:53
  • @JonSkeet: your suspicion is correct I think. And this is a common issue with `pytz`; there are *lots* of questions on SO where people stumbled across this "caveat" of the pytz API. [The docs](http://pytz.sourceforge.net/#localized-times-and-date-arithmetic) are clear about how to building a localized time - but it's hard to spot the warning sign that tells you what happens if you *dont't* use one of the two valid methods. – FObersteiner Oct 07 '20 at 06:55

1 Answers1

1

Why you get these "weired" offsets with pytz? Those are the first entries from the database for the respective time zones. With pytz, if you don't localize, these won't be adjusted to the time of your datetime object. Here's a nice blog post by Paul Ganssle giving more insights.

from datetime import datetime
import pytz

tz_Pacific = pytz.timezone('US/Pacific')
tz_Tasmania = pytz.timezone('Australia/Tasmania')

# note the LMT for local mean time:
print(repr(tz_Pacific))
print(repr(tz_Tasmania))
# <DstTzInfo 'US/Pacific' LMT-1 day, 16:07:00 STD> 
# <DstTzInfo 'Australia/Tasmania' LMT+9:49:00 STD>

# correctly localized you get
time1 = tz_Pacific.localize(datetime(2020, 10, 7, 18, 0, 0))
time2 = tz_Tasmania.localize(datetime(2020, 10, 7, 14, 20, 21))
print(time1)
print(time2)
# 2020-10-07 18:00:00-07:00
# 2020-10-07 14:20:21+11:00

Further remarks:

FObersteiner
  • 22,500
  • 8
  • 42
  • 72