Skip to content

Commit 4f7a900

Browse files
committed
gh-151770: Fix datetime.fromisoformat() assertion on an out-of-range month with a 24:00 time
The 24:00 midnight-rollover path validated only the upper month bound before calling days_in_month(), so a month below 1 reached assert(month >= 1) on a debug build (and AssertionError in the pure Python implementation). Add the missing lower bound to both so an out-of-range month consistently raises ValueError.
1 parent aa5b164 commit 4f7a900

4 files changed

Lines changed: 6 additions & 2 deletions

File tree

Lib/_pydatetime.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1987,7 +1987,7 @@ def fromisoformat(cls, date_string):
19871987
if became_next_day:
19881988
year, month, day = date_components
19891989
# Only wrap day/month when it was previously valid
1990-
if month <= 12 and day <= (days_in_month := _days_in_month(year, month)):
1990+
if 1 <= month <= 12 and day <= (days_in_month := _days_in_month(year, month)):
19911991
# Calculate midnight of the next day
19921992
day += 1
19931993
if day > days_in_month:

Lib/test/datetimetester.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3773,6 +3773,7 @@ def test_fromisoformat_fails_datetime_valueerror(self):
37733773
"2009-04-01T12:30:90", # Second out of range
37743774
"2009-04-01T12:90:45", # Minute out of range
37753775
"2009-04-01T25:30:45", # Hour out of range
3776+
"2009-00-01T24:00:00", # Month out of range (below)
37763777
"2009-13-01T24:00:00", # Month out of range
37773778
"9999-12-31T24:00:00", # Year out of range
37783779
]
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
Fix :meth:`datetime.datetime.fromisoformat` raising an unexpected error on an
2+
out-of-range month combined with a ``24:00`` time, such as
3+
``"2009-00-01T24:00:00"``. It now consistently raises :exc:`ValueError`.

Modules/_datetimemodule.c

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6144,7 +6144,7 @@ datetime_datetime_fromisoformat_impl(PyTypeObject *type, PyObject *string)
61446144
goto error;
61456145
}
61466146

6147-
if ((hour == 24) && (month <= 12)) {
6147+
if ((hour == 24) && (month >= 1) && (month <= 12)) {
61486148
int d_in_month = days_in_month(year, month);
61496149
if (day <= d_in_month) {
61506150
if (minute == 0 && second == 0 && microsecond == 0) {

0 commit comments

Comments
 (0)