I'm trying to serialize time-objects to ISO8601 format while preserving their timezone information with Python 3.8.
The documentation for time.isoformat states:
time.isoformat(timespec='auto')Return a string representing the time in ISO 8601 format, one of:
HH:MM:SS.ffffff, ifmicrosecondis not 0HH:MM:SS, ifmicrosecondis 0HH:MM:SS.ffffff+HH:MM[:SS[.ffffff]], ifutcoffset()does not returnNoneHH:MM:SS+HH:MM[:SS[.ffffff]], ifmicrosecondis 0 andutcoffset()does not returnNone
As far as I understand from that documentation I just have to generate a time-object whose utcoffset() isn't None to get the timezone information as part of the ISO8601-formatted string. That works fine when using datetime.timezone.utc as timezone:
>>> from datetime import time, timezone
>>> t = time(1, 2, 3, tzinfo=timezone.utc)
>>> t
datetime.time(1, 2, 3, tzinfo=datetime.timezone.utc)
>>> t.utcoffset()
datetime.timedelta(0)
>>> t.isoformat()
'01:02:03+00:00'
However as soon as I want to use a timezone which isn't provided by the Python standard library, that doesn't seem to work anymore. I tried dateutil and pytz and in both cases got the same result:
>>> from datetime import time
>>> from dateutil.tz import gettz
>>> t = time(1, 2, 3, tzinfo=gettz("US/Eastern"))
>>> t
datetime.time(1, 2, 3, tzinfo=tzfile('/usr/share/zoneinfo/US/Eastern'))
>>> t.utcoffset()
>>> t.isoformat()
'01:02:03'
>>> from datetime import time
>>> from pytz import timezone
>>> t = time(1, 2, 3, tzinfo=timezone("US/Eastern"))
>>> t
datetime.time(1, 2, 3, tzinfo=<DstTzInfo 'US/Eastern' LMT-1 day, 19:04:00 STD>)
>>> t.utcoffset()
>>> t.isoformat()
'01:02:03'
I also tried using time.strftime() instead, however that doesn't solve my problem either:
>>> from datetime import time
>>> from dateutil.tz import gettz
>>> t = time(1, 2, 3, tzinfo=gettz("US/Eastern"))
>>> t.strftime("%H:%M:%S%z")
'01:02:03'
Why is that the case and how can I solve this issue?