[New-bugs-announce] [issue43237] datetime.__eq__ returns true when timezones don't match

Richard Wise report at bugs.python.org
Mon Feb 15 23:52:32 EST 2021

New submission from Richard Wise <richardwise25 at gmail.com>:

from datetime import datetime, timezone, timedelta

datetime_in_sgt = datetime(2021, 2, 16, 8, 0, 0, tzinfo=timezone(timedelta(hours=8)))
datetime_in_utc = datetime(2021, 2, 16, 0, 0, 0, tzinfo=timezone.utc)

print(datetime_in_sgt == datetime_in_utc)

Expected: False
Actual: True

Although these two datetimes represent the same instant on the timeline, they are not identical because they use different timezones. This means that when unit testing timezone handling, tests will incorrectly pass despite data being returned in UTC instead of the requested timezone, so we need to write code such as this:

# Timestamp comparison
self.assertEqual(datetime_in_sgt, datetime_in_utc)
# Timezone comparison
self.assertEqual(datetime_in_sgt.tzinfo, datetime_in_utc.tzinfo)

This is confusing and non-intuitive.

For examples of how other languages handle such comparison, can refer to: https://docs.oracle.com/javase/8/docs/api/java/time/ZonedDateTime.html#equals-java.lang.Object- and 

components: Library (Lib)
messages: 387087
nosy: Woodz
priority: normal
severity: normal
status: open
title: datetime.__eq__ returns true when timezones don't match
versions: Python 3.8

Python tracker <report at bugs.python.org>

More information about the New-bugs-announce mailing list