Skip to content

Commit 8f26a79

Browse files
miss-islingtonvstinnermgorny
authored
gh-130959: Reject whitespace in fractions, in pure Python fromisoformat() (GH-130962) (GH-131076) (#131086)
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`). (cherry picked from commit 33494b4) (cherry picked from commit 27fd328) Co-authored-by: Victor Stinner <[email protected]> Co-authored-by: Michał Górny <[email protected]>
1 parent 3f226c5 commit 8f26a79

File tree

3 files changed

+11
-3
lines changed

3 files changed

+11
-3
lines changed

Lib/_pydatetime.py

+2-3
Original file line numberDiff line numberDiff line change
@@ -402,6 +402,8 @@ def _parse_hh_mm_ss_ff(tstr):
402402
raise ValueError("Invalid microsecond component")
403403
else:
404404
pos += 1
405+
if not all(map(_is_ascii_digit, tstr[pos:])):
406+
raise ValueError("Non-digit values in fraction")
405407

406408
len_remainder = len_str - pos
407409

@@ -413,9 +415,6 @@ def _parse_hh_mm_ss_ff(tstr):
413415
time_comps[3] = int(tstr[pos:(pos+to_parse)])
414416
if to_parse < 6:
415417
time_comps[3] *= _FRACTION_CORRECTION[to_parse-1]
416-
if (len_remainder > to_parse
417-
and not all(map(_is_ascii_digit, tstr[(pos+to_parse):]))):
418-
raise ValueError("Non-digit values in unparsed fraction")
419418

420419
return time_comps
421420

Lib/test/datetimetester.py

+6
Original file line numberDiff line numberDiff line change
@@ -3325,6 +3325,9 @@ def test_fromisoformat_fails_datetime(self):
33253325
'2009-04-19T12:30:45.123456-05:00a', # Extra text
33263326
'2009-04-19T12:30:45.123-05:00a', # Extra text
33273327
'2009-04-19T12:30:45-05:00a', # Extra text
3328+
'2009-04-19T12:30:45.400 +02:30', # Space between ms and timezone (gh-130959)
3329+
'2009-04-19T12:30:45.400 ', # Trailing space (gh-130959)
3330+
'2009-04-19T12:30:45. 400', # Space before fraction (gh-130959)
33283331
]
33293332

33303333
for bad_str in bad_strs:
@@ -4377,6 +4380,9 @@ def test_fromisoformat_fails(self):
43774380
'12:30:45.123456-', # Extra at end of microsecond time
43784381
'12:30:45.123456+', # Extra at end of microsecond time
43794382
'12:30:45.123456+12:00:30a', # Extra at end of full time
4383+
'12:30:45.400 +02:30', # Space between ms and timezone (gh-130959)
4384+
'12:30:45.400 ', # Trailing space (gh-130959)
4385+
'12:30:45. 400', # Space before fraction (gh-130959)
43804386
]
43814387

43824388
for bad_str in bad_strs:
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
Fix pure-Python implementation of :func:`datetime.time.fromisoformat` to reject
2+
times with spaces in fractional part (for example, ``12:34:56.400 +02:00``),
3+
matching the C implementation. Patch by Michał Gorny.

0 commit comments

Comments
 (0)