Skip to content

datetime with ZoneInfo: comparison bug #92706

Closed

Description

@yl770

When you compare two datetime.datetime objects that use Python's new zoneinfo.ZoneInfo as the tzinfo, you get the incorrect answer if it's on the day the clocks change.

# Bug in Python's datetime.datetime with zoneinfo.ZoneInfo

from datetime import datetime, timezone
from zoneinfo import ZoneInfo

# let's construct two datetime objects on the day we change the clocks. Both are 1:30AM. The 'fold' argument tells us
# whether the time is before or after the change between Daylight Savings and Standard times
fold_is_0 = datetime(2022, 11, 6, 1, 30, tzinfo=ZoneInfo('America/New_York'), fold=0)  # half hour before clock changes
fold_is_1 = datetime(2022, 11, 6, 1, 30, tzinfo=ZoneInfo('America/New_York'), fold=1)  # half hour after clock change
print(f'0: {fold_is_0}')  # 0: 2022-11-06 01:30:00-04:00
print(f'1: {fold_is_1}')  # 1: 2022-11-06 01:30:00-05:00
# The object have different UTC offsets. This means that fold_is_0 is a EARLIER moment in time than fold_is_1.

# When we compare their Unix times and ISO, we see that fold_is_0 == fold_is_1 is False
print(f'2: {fold_is_0.timestamp() == fold_is_1.timestamp()}')  # 2: False
print(f'3: {fold_is_0.isoformat() == fold_is_1.isoformat()}')  # 3: False
# so far, so good

# We expect fold_is_0 == fold_is_1 to be False since the fold_is_1 happens on hour later. However, Python gets
# it wrong. We expect to see False in this print statement:
print(f'4: {fold_is_0 == fold_is_1}')  # 4: True
# The actual result is True! This is a bug!!!

More proof that it's a bug

If you're not convinced yet, then add this to the script:

# To further prove this is a bug, let's move to UTC and try again. This changes the timezone we're using, but not the
# moment in time that the datetime represent
fold_is_0 = fold_is_0.astimezone(ZoneInfo('UTC'))
fold_is_1 = fold_is_1.astimezone(ZoneInfo('UTC'))
# Now, we not get the correct answer. We expect to see False in this print statement, and we do:
print(f'5: {fold_is_0 == fold_is_1}')  # 5: False
# This is confirmed when we use Unix time and ISO. We expect False in this print statement too, and it is:
print(f'6: {fold_is_0.timestamp() == fold_is_1.timestamp()}')  # 6: False
print(f'7: {fold_is_0.isoformat() == fold_is_1.isoformat()}')  # 7: False

# To prove again that this is a bug, we'll show that changing the timezone offset SHOULD cause Python to return
# that fold_is_0 == fold_is_1 is False
fold_is_1 = datetime(2022, 11, 6, 1, 30, tzinfo=ZoneInfo('America/New_York'), fold=1)  # return to original value
# another datetime that SHOULD be the same as fold_is_1
corrected_fold_is_1 = datetime(2022, 11, 6, 1, 30, tzinfo=timezone(fold_is_1.utcoffset(), 'Corrected offset'))

# Now we get the correct answer. We expect fold_is_0 == corrected_fold_is_1 to be False, and it is False.
print(f'8: {fold_is_0 == corrected_fold_is_1}')  # 8: False
# Indeed, fold_is_1 and corrected_fold_is_1 both refer to the same moment in time, as shown with their Unix time and ISO
print(f'9: {fold_is_1.timestamp() == corrected_fold_is_1.timestamp()}')  # 9: True
print(f'10: {fold_is_1.isoformat() == corrected_fold_is_1.isoformat()}')  # 10: True

# So, yes, this IS a bug


A workaround:

Instead of comparing two datetimes: a >= b, use a workaround of comparing like this: a.timestamp() >= b.timestamp()

Environment:

Python 3.10.4 on macOS Monterey Ver 12.3.1

Activity

  1. added
    type-bug
    on May 12, 2022
  2. pganssle commented on May 13, 2022

    @pganssle
    Member

    Thank you for your bug report! Unfortunately, this is in fact the desired behavior, as explicitly detailed in PEP 495:

    As explained in the previous paragraph, timedelta addition ignores both fold and tzinfo attributes and so does intra-zone or naive datetime subtraction.

    This is an intra-zone comparison, and so fold is simply ignored, and the naïve portion of the datetimes are compared and found to be equal. This can also be seen in footnote 4 under datetime's "supported operations" section (link goes to closest anchor link I could find):

    If both comparands are aware, and have the same tzinfo attribute, the common tzinfo attribute is ignored and the base datetimes are compared. If both comparands are aware and have different tzinfo attributes, the comparands are first adjusted by subtracting their UTC offsets (obtained from self.utcoffset()).

    More details on aware datetime comparison and arithmetic semantics here and here.

    If you want to compare the absolute position in time of two datetimes, you should convert to UTC or some other "absolute position in time" representation like .timestamp(). This is mostly an unfortunate oversight and it would be nice if we could change it, but I don't believe that we can do so in a backwards-compatible manner.

    There is a related annoyance documented only in PEP 495 (we should really add this to the documentation:

    Whenever one or both of the operands in inter-zone comparison is such that its utcoffset() depends on the value of its fold fold attribute, the result is False. [6]

    >>> from datetime import datetime, timezone
    >>> from zoneinfo import ZoneInfo
    >>> dt = datetime(2022, 11, 6, 1, 30, tzinfo=ZoneInfo('America/New_York'), fold=0)
    >>> dt == dt.astimezone(timezone.utc)
    False

    In the case you detailed, the result was True even though the two datetimes represent different times on the absolute number line (because they have the same "wall time" representation). Normally you can get around this by converting even one of them to UTC, since that would either make the comparison UTC vs UTC (no problem if it's intra-zone) or it would use inter-zone rules and you'd get an absolute time comparison, but in this case since dt.utcoffset() depends on the value of fold, it will always return False in an inter-zone comparison. This is one of the worst warts on datetime comparison, but again our hands tend to be tied due to backwards compatibility. It's probably best to just always explicitly do comparisons with either UTC or naïve datetimes, depending on your preferred semantics.

  3. yl770 commented on May 18, 2022

    @yl770
    Author

    Thanks so much for clarifying that, @pganssle! Here's an idea how this might be changed in a backward-compatible manner. This idea is actually more Pythonic since it follows PEP8 capitalization:

    class DateTime(datetime.datetime):
        """Modification of Python's datetime.datetime to produce an error in situations where the result doesn't make sense
        See: https://github.com/python/cpython/issues/92706
        """
        def __eq__(self, other):
            raise NotImplementedError('BUG IN PYTHON: if you compare two datetime objects, eg x == b, it sometimes gives '
                                      'the wrong answer. A workaround is to compare x.timestamp() == b.timestamp().')
    
        # do same for __ne__, __gt__, __ge__, __lt__, __le__
    

    Just keep in mind, that if something like this is implemented, then it's a really good idea to research for any other issues with datetime.datetime and to handle them too. It would be hard to do that again: replacing datetime with DateTime is OK, but replacing DateTime with DateTime2 would be a drag!

  4. tuttle commented on Sep 25, 2022

    @tuttle

    I bumped into this today and described a related problem in pganssle/pytz-deprecation-shim#29 - so comparing datetimes is obviously very unfortunate.

    So wouldn't it be useful to document the problem more explicitly and prominently in stdlib, and recommend how to correctly compare datetimes with timezones?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

type-bug

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions