diff --git a/Lib/_pydatetime.py b/Lib/_pydatetime.py index 67f195bff93a00..fedc3447711ba1 100644 --- a/Lib/_pydatetime.py +++ b/Lib/_pydatetime.py @@ -1953,7 +1953,7 @@ def fromisoformat(cls, date_string): if became_next_day: year, month, day = date_components # Only wrap day/month when it was previously valid - if 1 <= month <= 12 and day <= (days_in_month := _days_in_month(year, month)): + if 1 <= month <= 12 and 1 <= day <= (days_in_month := _days_in_month(year, month)): # Calculate midnight of the next day day += 1 if day > days_in_month: diff --git a/Lib/test/datetimetester.py b/Lib/test/datetimetester.py index 11050fc8d4332a..8d78ab0ba9a17b 100644 --- a/Lib/test/datetimetester.py +++ b/Lib/test/datetimetester.py @@ -3724,7 +3724,8 @@ def test_fromisoformat_datetime_examples(self): tzinfo=timezone(timedelta(seconds=10)))), ('2025-01-02T24:00:00', self.theclass(2025, 1, 3, 0, 0, 0)), ('2025-01-31T24:00:00', self.theclass(2025, 2, 1, 0, 0, 0)), - ('2025-12-31T24:00:00', self.theclass(2026, 1, 1, 0, 0, 0)) + ('2025-12-31T24:00:00', self.theclass(2026, 1, 1, 0, 0, 0)), + ('0000-12-31T24:00:00', self.theclass(1, 1, 1, 0, 0, 0)), ] for input_str, expected in examples: @@ -3822,9 +3823,12 @@ def test_fromisoformat_fails_datetime_valueerror(self): self.theclass.fromisoformat(bad_str) # days out of range have their own error message, see issue 70647 - with self.assertRaises(ValueError) as msg: - self.theclass.fromisoformat("2009-04-32T24:00:00") - self.assertIn(f"day 32 must be in range 1..30 for month 4 in year 2009", str(msg.exception)) + for day in (0, 32): + with self.subTest(day=day): + with self.assertRaises(ValueError) as msg: + self.theclass.fromisoformat(f"2009-04-{day:02d}T24:00:00") + self.assertIn(f"day {day} must be in range 1..30 for month 4 in year 2009", + str(msg.exception)) def test_fromisoformat_fails_surrogate(self): # Test that when fromisoformat() fails with a surrogate character as diff --git a/Misc/NEWS.d/next/Library/2026-11-20-13-51-31.gh-issue-162306.ys64EX.rst b/Misc/NEWS.d/next/Library/2026-11-20-13-51-31.gh-issue-162306.ys64EX.rst new file mode 100644 index 00000000000000..78e0bb43b0eb1e --- /dev/null +++ b/Misc/NEWS.d/next/Library/2026-11-20-13-51-31.gh-issue-162306.ys64EX.rst @@ -0,0 +1,3 @@ +Fix :meth:`datetime.datetime.fromisoformat` to raise :exc:`ValueError` for a +day of ``0`` combined with a ``24:00`` time, instead of returning the +following date. diff --git a/Modules/_datetimemodule.c b/Modules/_datetimemodule.c index 23eec54cb6c182..6788d28be98d0e 100644 --- a/Modules/_datetimemodule.c +++ b/Modules/_datetimemodule.c @@ -6165,7 +6165,7 @@ datetime_datetime_fromisoformat_impl(PyTypeObject *type, PyObject *string) if ((hour == 24) && (month >= 1 && month <= 12)) { int d_in_month = days_in_month(year, month); - if (day <= d_in_month) { + if (day >= 1 && day <= d_in_month) { if (minute == 0 && second == 0 && microsecond == 0) { // Calculate midnight of the next day hour = 0;