diff --git a/src/pendulum/tz/timezone.py b/src/pendulum/tz/timezone.py index e46e13df1..131ad3073 100644 --- a/src/pendulum/tz/timezone.py +++ b/src/pendulum/tz/timezone.py @@ -69,6 +69,9 @@ def __new__(cls, key: str) -> Self: def __eq__(self, other: object) -> bool: return isinstance(other, Timezone) and self.key == other.key + def __hash__(self) -> int: + return hash((Timezone, self.key)) + @property def name(self) -> str: return self.key @@ -178,6 +181,9 @@ def __init__(self, offset: int, name: str | None = None) -> None: def __eq__(self, other: object) -> bool: return isinstance(other, FixedTimezone) and self._offset == other._offset + def __hash__(self) -> int: + return hash((FixedTimezone, self._offset)) + @property def name(self) -> str: return self._name diff --git a/tests/tz/test_timezone.py b/tests/tz/test_timezone.py index 3f0901681..63840692c 100644 --- a/tests/tz/test_timezone.py +++ b/tests/tz/test_timezone.py @@ -13,6 +13,7 @@ from pendulum.tz import fixed_timezone from pendulum.tz.exceptions import AmbiguousTime from pendulum.tz.exceptions import NonExistingTime +from pendulum.tz.timezone import FixedTimezone from tests.conftest import assert_datetime @@ -47,6 +48,11 @@ def test_equality(): assert timezone("Europe/Paris") != timezone("Europe/Berlin") +def test_hash(): + assert hash(timezone("Europe/Paris")) == hash(timezone("Europe/Paris")) + assert len({timezone("Europe/Paris"), timezone("Europe/Paris")}) == 1 + + def test_skipped_time_with_pre_rule(): dt = datetime(2013, 3, 31, 2, 30, 45, 123456, fold=0) tz = timezone("Europe/Paris") @@ -409,6 +415,14 @@ def test_fixed_equality(): assert fixed_timezone(19800) != fixed_timezone(19801) +def test_fixed_hash(): + assert hash(fixed_timezone(19800)) == hash(fixed_timezone(19800)) + assert fixed_timezone(19800) == FixedTimezone(19800, name="custom"), ( + "Pre-condition: name ignored for FixedTimezone" + ) + assert len({fixed_timezone(19800), FixedTimezone(19800, name="custom")}) == 1 + + def test_just_before_last_transition(): tz = pendulum.timezone("Asia/Shanghai") dt = datetime(1991, 4, 20, 1, 49, 8, fold=0)