Need to work with timezones in #Python?
Don’t use pytz! Use zoneinfo.
It’s included in the standard library from Python 3.9 onward and pip install-able if you’re on 3.8.
Big NOTE: If your code needs to run on Windows, you’ll also need to pip install tzdata too!
What’s wrong with pytz? Silent bugs due to datetime arithmetic issues.
>>> pt = pytz.timezone("America/Los_Angeles") >>> mar1 = pt.localize(datetime(2023, 3, 1, 10, 0)) >>> apr1 = pt.localize(datetime(2023, 4, 1, 10, 0)) >>> apr1 < mar1 + timedelta(days=31) True
These two times should be equal, but instead one is an hour before the other due to their timezone offsets.
>>> print(apr1_10am) 2023-04-01 10:00:00-07:00 >>> print(march1_10am + timedelta(days=31)) 2023-04-01 10:00:00-08:00
That second one is in PST time during PDT!
You might say “well you’re supposed to do datetime arithmetic only on UTC times”.
True… but it doesn’t have to be that way!
That’s a limitation with the way pytz works and it can cause all sorts of silent bugs.
zoneinfo will do the right thing here instead.
Tweet from Trey Hunner