gweis / isodate

ISO 8601 date/time parser
BSD 3-Clause "New" or "Revised" License
148 stars 58 forks source link

tz_isoformat works wrong with datetime.timezone.utc #89

Open an42rus opened 2 months ago

an42rus commented 2 months ago

There is an issue with replacing of tz info from +00:00 to Z.

timezone.dst(dt) Always returns None.

import isodate
import pytz
from datetime import datetime, timezone

timezone_datetime = datetime.now(tz=timezone.utc)
pytz_datetime = datetime.now(tz=pytz.utc)

isodate.datetime_isoformat(timezone_datetime)
# '2024-07-02T06:06:02+00:00'

isodate.datetime_isoformat(pytz_datetime)
# '2024-07-02T06:06:02Z'

timezone_datetime.dst()
# None

pytz_datetime.dst()
# datetime.timedelta(0)

It seems you need to add extra checking of dst for None value here

mgmartian commented 2 months ago

We've been using isodate for many years, and oddly enough just ran into the same issue as @an42rus when switching from pytz to zoneinfo / timezone.utc.

Here's the little hack we put in place:

        from isodate import DATE_EXT_COMPLETE, datetime_isoformat, TIME_EXT_COMPLETE, TZ_EXT
        from datetime import timezone

        if dt.tzinfo is timezone.utc:
            tz_suffix = 'Z'
        else:
            tz_suffix = TZ_EXT

        return datetime_isoformat(dt, f"{DATE_EXT_COMPLETE}T{TIME_EXT_COMPLETE}{tz_suffix}")