python / cpython

The Python programming language
https://www.python.org
Other
62.4k stars 29.96k forks source link

Unexpected results when comparing time instances #98509

Open chihsuanwu opened 1 year ago

chihsuanwu commented 1 year ago

Bug report

When comparing two time instances with different timezone, there are some unexpected result in some cases.

from datetime import datetime, time, timezone, timedelta

# Two time instances with the same absolute time in different time zones
t1 = time(hour = 0, tzinfo = timezone(timedelta(hours=1)))
t2 = time(hour = 7, tzinfo = timezone(timedelta(hours=8)))

print(t1 == t2) # True

# Another time instances with the same absolute time in different time zones, and local date is different
t3 = time(hour = 23, tzinfo = timezone(timedelta(hours=0)))
t4 = time(hour = 7, tzinfo = timezone(timedelta(hours=8)))

print(t3 == t4) # False, UNEXPECTED

# Two datetime instances with the same absolute time in different time zones and different local date
d1 = datetime(2022, 10, 10, hour = 23, tzinfo = timezone(timedelta(hours=0)))
d2 = datetime(2022, 10, 11, hour = 7, tzinfo = timezone(timedelta(hours=8)))

print(d1 == d2) # True, make sense
print(d1.timetz() == d2.timetz()) # False, UNEXPECTED

If two times with different timezones have the same absolute time, then thay should be equle. However, when the local dates of the two times are different, the comparison will be false even if the absolute time is the same.

As in the code above, the comparison between two datetimes has expected result, even though their local dates is different. However if we compare the time extracted from these two datetimes, the result will be false.

Your environment

pganssle commented 1 year ago

This seems reasonable, though changing the semantics of comparison like this is usually fraught because of backwards compatibility concerns.

I am very tempted to say that maybe we should do this even despite backwards compatibility concerns because this seems like it's probably the right thing to do, the documentation and tests are apparently ambiguous about it and I suspect that no one or almost no one is relying on the current behavior.

The fundamental issue here is that time zones should never have been attached to time objects in the first place, since they are ill-defined for a free floating time.

A closely related issue is this one: #61469, where arithmetic is not defined on time objects, and iirc it mostly comes down to uncertainty as to whether arithmetic should be modular.

@abalkin Do you know if the is the current semantics are deliberate, and if they are, is there a good reason?