Calling normalize() on DstTzInfo instances errors when dt.tzinfo is not BaseTzInfo subclass
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.
>>> tz = pytz.timezone(
>>> tz.normalize(dt)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Users/
offset = dt.tzinfo.
AttributeError: 'datetime.timezone' object has no attribute '_utcoffset'
This is relatively easy to fix and would improve support and compatibility with the standard library.