Skip to content

Fix JSON encoding of datetimes with zoneinfo tzinfos - #534

Merged
jcrist merged 1 commit into
mainfrom
fix-datetime-zoneinfo
Aug 24, 2023
Merged

jcrist merged 1 commit into
mainfrom
fix-datetime-zoneinfo

Conversation

@jcrist

@jcrist jcrist commented Aug 24, 2023

Copy link
Copy Markdown
Member

This fixes a bug where datetime objects with zoneinfo.ZoneInfo instances set for tzinfo would encode as UTC, ignoring the zoneinfo. This issue was due to datetime.utcoffset being called with None instead of the datetime instance. This worked fine for other tzinfo types (like datetime.timezone) since those use fixed offsets that aren't date aware.

This also fixes a bug where datetime.time instances with a tzinfo that returns None from datetime.time.utcoffset were treated as UTC rather than naive. Quoting from the standard library docs:

A datetime object d is aware if both of the following hold:

  1. d.tzinfo is not None
  2. d.tzinfo.utcoffset(d) does not return None

Otherwise, d is naive.

A time object t is aware if both of the following hold:

  1. t.tzinfo is not None
  2. t.tzinfo.utcoffset(None) does not return None.

Otherwise, t is naive.

Both bugs fixed above were due to incorrect behavior around the 2nd condition using utcoffset.

Fixes #533.

This fixes a bug where datetime objects with `zoneinfo.ZoneInfo`
instances set for `tzinfo` would encode as UTC, ignoring the zoneinfo.
This issue was due to `datetime.utcoffset` being called with `None`
instead of the `datetime` instance. This worked fine for other `tzinfo`
types (like `datetime.timezone`) since those use fixed offsets that
aren't date aware.

This also fixes a bug where `datetime.time` instances with a `tzinfo`
that returns `None` from `datetime.time.utcoffset` were treated as UTC
rather than naive. Quoting from the standard library docs:

> A datetime object d is aware if both of the following hold:
>
> 1. d.tzinfo is not None
> 2. d.tzinfo.utcoffset(d) does not return None
>
> Otherwise, d is naive.
>
> A time object t is aware if both of the following hold:
>
> 1. t.tzinfo is not None
> 2. t.tzinfo.utcoffset(None) does not return None.
>
> Otherwise, t is naive.

Both bugs fixed above were due to incorrect behavior around the 2nd
condition using `utcoffset`.
@jcrist
jcrist force-pushed the fix-datetime-zoneinfo branch from b65b7cd to ee2b306 Compare August 24, 2023 14:48
@jcrist
jcrist merged commit 5414de7 into main Aug 24, 2023
@jcrist
jcrist deleted the fix-datetime-zoneinfo branch August 24, 2023 15:05
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

JSON encoder does not respect ZoneInfo (the IANA time zone database) when encoding datetime objects.

1 participant