Skip to content

Commit 45a0043

Browse files
miss-islingtontonghuarootStanFromIreland
authored
[3.15] gh-151770: Fix datetime.fromisoformat() on an out-of-range month w/ a 24:00 time (GH-151771) (#151809)
(cherry picked from commit 1fb874c) Co-authored-by: tonghuaroot (童话) <tonghuaroot@gmail.com> Co-authored-by: Stan Ulbrych <stan@python.org>
1 parent ba8548c commit 45a0043

4 files changed

Lines changed: 7 additions & 3 deletions

File tree

Lib/_pydatetime.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -55,7 +55,7 @@ def _days_before_year(year):
5555

5656
def _days_in_month(year, month):
5757
"year, month -> number of days in that month in that year."
58-
assert 1 <= month <= 12, month
58+
assert 1 <= month <= 12, f"month must be in 1..12, not {month}"
5959
if month == 2 and _is_leap(year):
6060
return 29
6161
return _DAYS_IN_MONTH[month]
@@ -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 below range
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 :exc:`AssertionError`
2+
instead of :exc:`ValueError` for an out-of-range month combined with a
3+
``24:00`` time.

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)