Calling normalize() on DstTzInfo instances errors when dt.tzinfo is not BaseTzInfo subclass

Bug #1874724 reported by Lucas Lofaro
6
This bug affects 1 person
Affects Status Importance Assigned to Milestone
pytz
New
Undecided
Unassigned

Bug Description

I came across an interesting issue involving incompatibility between pytz timezones and standard datetime.timezone objects. I ran into an error when attempting to normalize a datetime instance whose tzinfo attribute was an instance datetime.timezone. In particular, this issues arises when calling the normalize() method of DstTzInfo objects. Based on the implementation, the normalize() method expects the tzinfo attribute to derive from BaseTzInfo (it assumes the object has s _utcoffset attribute). While this may not be something people run into a lot, this method should support instances of the timezone class from the standard library.

I encountered this while working with the FastAPI framework, which has native support for parsing datetime objects from HTTP requests. Naturally, the framework uses datetime.timezone objects for timezone-aware datetimes in order to avoid dependence on a third party library. As a result, attempting to normalize to a DST timezone object fails hard.

>>> dt = datetime.datetime(2019, 8, 4, tzinfo=datetime.timezone.utc)
>>> tz = pytz.timezone('America/Los_Angeles')
>>> tz.normalize(dt)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/Users/lucaslofaro/Work/axiom-exergy/visualizer/venv/lib/python3.7/site-packages/pytz/tzinfo.py", line 252, in normalize
    offset = dt.tzinfo._utcoffset
AttributeError: 'datetime.timezone' object has no attribute '_utcoffset'

This is relatively easy to fix and would improve support and compatibility with the standard library.

To post a comment you must log in.
This report contains Public information  
Everyone can see this information.

Other bug subscribers

Remote bug watches

Bug watches keep track of this bug in other bug trackers.