An offset-aware datetime.datetime.time() result does not contain the timezone of the original object. This leads to problems when trying to compare them with offset-aware times:
>>>fromdatetimeimportdatetime, time, timezone, timedelta>>>x=datetime(2022, 12, 20, 0, 0, 0, tzinfo=timezone(timedelta(hours=5)))
>>>x.tzinfo# fine: x contains a proper timezone (is offset-aware)datetime.timezone(datetime.timedelta(seconds=18000))
>>>x.time() # bug: x.time() is not offset-aware anymore...datetime.time(0, 0)
>>>x.time().tzinfo# ...because it does NOT retain the timezone info...>>>x.time() <time(tzinfo=timezone(timedelta(hours=-2))) # ...so it can NOT be compared with offset-aware times.Traceback (mostrecentcalllast):
File"<stdin>", line1, in<module>TypeError: can'tcompareoffset-naiveandoffset-awaretimes
I would have expected that
offset-naive datetime.datetime.time() returns an offset-naive time object, and
offset-aware datetime.datetime.time() returns an offset-aware time object,
because with the current (faulty) behavior, we loose important specificity.
Your environment
CPython versions tested on: 3.10, 3.11
Operating system and architecture: Linux amd64
The text was updated successfully, but these errors were encountered:
>>> help(x.time)
Help on built-in function time:
time(...) method of datetime.datetime instance
Return time object with same time but with tzinfo=None.
>>> help(x.timetz)
Help on built-in function timetz:
timetz(...) method of datetime.datetime instance
Return time object with same time and tzinfo.
Okay, there's an explicit method to get the tz-aware time. I would not have designed it like this (explicit is better than implicit and an implicit change of an offset-aware time into offset-naive feels wrong), but my problem is solved.
LarsKumbier commentedDec 20, 2022
Bug report
An offset-aware datetime.datetime.time() result does not contain the timezone of the original object. This leads to problems when trying to compare them with offset-aware times:
I would have expected that
because with the current (faulty) behavior, we loose important specificity.
Your environment
The text was updated successfully, but these errors were encountered: