Skip to content

Commit 205dfff

Browse files
[3.14] gh-152060: Fix _pydatetime.fromisoformat() raising AssertionError on invalid lengths (GH-152061) (#152786)
Co-authored-by: Stan Ulbrych <stan@python.org>
1 parent 5708818 commit 205dfff

3 files changed

Lines changed: 6 additions & 1 deletion

File tree

Lib/_pydatetime.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -358,7 +358,8 @@ def _find_isoformat_datetime_separator(dtstr):
358358
def _parse_isoformat_date(dtstr):
359359
# It is assumed that this is an ASCII-only string of lengths 7, 8 or 10,
360360
# see the comment on Modules/_datetimemodule.c:_find_isoformat_datetime_separator
361-
assert len(dtstr) in (7, 8, 10)
361+
if len(dtstr) not in (7, 8, 10):
362+
raise ValueError("Invalid isoformat string")
362363
year = int(dtstr[0:4])
363364
has_sep = dtstr[4] == '-'
364365

Lib/test/datetimetester.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3581,6 +3581,7 @@ def test_fromisoformat_fails_datetime(self):
35813581
'2009-04-19T12:30:45.400 +02:30', # Space between ms and timezone (gh-130959)
35823582
'2009-04-19T12:30:45.400 ', # Trailing space (gh-130959)
35833583
'2009-04-19T12:30:45. 400', # Space before fraction (gh-130959)
3584+
'2020-2020', # Ambiguous 9-char date portion
35843585
]
35853586

35863587
for bad_str in bad_strs:
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 some malformed strings in the pure-Python
3+
implementation, matching the C implementation.

0 commit comments

Comments
 (0)