Skip to content

Commit bfbc3b9

Browse files
committed
gh-130959: Reject whitespace in fractions, in pure Python fromisoformat()
Fix the pure Python implementation of `fromisoformat()` to reject any non-digit characters, including whitespace, in the fractional part of time specification. This makes the behavior consistent with the C implementation, and prevents incorrect parsing of these fractions (e.g. `.400 ` would be misinterpreted as `.04`).
1 parent 12db452 commit bfbc3b9

File tree

2 files changed

+8
-3
lines changed

2 files changed

+8
-3
lines changed

Lib/_pydatetime.py

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -436,6 +436,8 @@ def _parse_hh_mm_ss_ff(tstr):
436436
raise ValueError("Invalid microsecond separator")
437437
else:
438438
pos += 1
439+
if not all(map(_is_ascii_digit, tstr[pos:])):
440+
raise ValueError("Non-digit values in fraction")
439441

440442
len_remainder = len_str - pos
441443

@@ -447,9 +449,6 @@ def _parse_hh_mm_ss_ff(tstr):
447449
time_comps[3] = int(tstr[pos:(pos+to_parse)])
448450
if to_parse < 6:
449451
time_comps[3] *= _FRACTION_CORRECTION[to_parse-1]
450-
if (len_remainder > to_parse
451-
and not all(map(_is_ascii_digit, tstr[(pos+to_parse):]))):
452-
raise ValueError("Non-digit values in unparsed fraction")
453452

454453
return time_comps
455454

Lib/test/datetimetester.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3556,6 +3556,9 @@ def test_fromisoformat_fails_datetime(self):
35563556
'9999-12-31T24:00:00.000000', # Year is invalid after wrapping due to 24:00
35573557
'2009-04-19T12:30Z12:00', # Extra time zone info after Z
35583558
'2009-04-19T12:30:45:334034', # Invalid microsecond separator
3559+
'2009-04-19T12:30:45.400 +02:30', # Space between ms and timezone (gh-130959)
3560+
'2009-04-19T12:30:45.400 ', # Trailing space (gh-130959)
3561+
'2009-04-19T12:30:45. 400', # Space before fraction (gh-130959)
35593562
]
35603563

35613564
for bad_str in bad_strs:
@@ -4773,6 +4776,9 @@ def test_fromisoformat_fails(self):
47734776
'12:30,5', # Decimal mark at end of minute
47744777
'12:30:45.123456Z12:00', # Extra time zone info after Z
47754778
'12:30:45:334034', # Invalid microsecond separator
4779+
'12:30:45.400 +02:30', # Space between ms and timezone (gh-130959)
4780+
'12:30:45.400 ', # Trailing space (gh-130959)
4781+
'12:30:45. 400', # Space before fraction (gh-130959)
47764782
]
47774783

47784784
for bad_str in bad_strs:

0 commit comments

Comments
 (0)