Skip to content

Commit af18abb

Browse files
tonghuarootmiss-islington
authored andcommitted
pythongh-152060: Fix _pydatetime.fromisoformat() raising AssertionError on invalid lengths (pythonGH-152061)
(cherry picked from commit ff781d5) Co-authored-by: tonghuaroot (童话) <tonghuaroot@gmail.com>
1 parent c3129e6 commit af18abb

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
@@ -3757,6 +3757,7 @@ def test_fromisoformat_fails_datetime(self):
37573757
'2009-04-19T12:30:45+00:00:90', # Time zone field out from range
37583758
'2009-04-19T12:30:45-00:90:00', # Time zone field out from range
37593759
'2009-04-19T12:30:45-00:00:90', # Time zone field out from range
3760+
'2020-2020', # Ambiguous 9-char date portion
37603761
]
37613762

37623763
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)