Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 31 additions & 0 deletions Lib/test/test_zoneinfo/test_zoneinfo.py
Original file line number Diff line number Diff line change
Expand Up @@ -316,6 +316,37 @@ def test_unambiguous(self):
self.assertEqual(dt.utcoffset(), offset.utcoffset, dt)
self.assertEqual(dt.dst(), offset.dst, dt)

def test_datetime_subclass_negative_components(self):
"""Regression test for gh-154892.

Datetime subclasses may return -1 for time components. The C
accelerator should treat -1 as a valid PyLong_AsLong() result unless
an exception is set, matching the pure-Python implementation.
"""
class MinusOneDateTime(datetime):
@property
def hour(self):
return -1

@property
def minute(self):
return -1

@property
def second(self):
return -1

zi = self.zone_from_key("UTC")
dt = MinusOneDateTime(2024, 1, 1, tzinfo=zi)

self.assertEqual(dt.utcoffset(), ZERO)
self.assertEqual(dt.dst(), ZERO)
self.assertEqual(dt.tzname(), "UTC")
self.assertEqual(
zi.fromutc(dt),
datetime(2024, 1, 1, tzinfo=zi),
)

def test_folds_and_gaps(self):
test_cases = []
for key in self.zones():
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
Fixed a bug in the C accelerator for :mod:`zoneinfo` where ``datetime``
subclasses returning ``-1`` for ``hour``, ``minute``, or ``second`` could
incorrectly raise an error due to ``PyLong_AsLong()`` sentinel handling.
6 changes: 3 additions & 3 deletions Modules/_zoneinfo.c
Original file line number Diff line number Diff line change
Expand Up @@ -2311,7 +2311,7 @@ get_local_timestamp(PyObject *dt, int64_t *local_ts)
}
hour = PyLong_AsLong(num);
Comment thread
BHUVANSH855 marked this conversation as resolved.
Py_DECREF(num);
if (hour == -1) {
if (hour == -1 && PyErr_Occurred()) {
return -1;
}

Expand All @@ -2321,7 +2321,7 @@ get_local_timestamp(PyObject *dt, int64_t *local_ts)
}
minute = PyLong_AsLong(num);
Py_DECREF(num);
if (minute == -1) {
if (minute == -1 && PyErr_Occurred()) {
return -1;
}

Expand All @@ -2331,7 +2331,7 @@ get_local_timestamp(PyObject *dt, int64_t *local_ts)
}
second = PyLong_AsLong(num);
Py_DECREF(num);
if (second == -1) {
if (second == -1 && PyErr_Occurred()) {
return -1;
}
}
Expand Down
Loading