python / cpython

The Python programming language
https://www.python.org
Other
62.35k stars 29.94k forks source link

datetime.datetime.isoformat parses input incorrectly #115225

Open xitop opened 7 months ago

xitop commented 7 months ago

Bug report

Bug description:

import datetime as dt
print(dt.time.fromisoformat("T1250.50"))

Actual result is 12:50:00.500000, but according to ISO 8601 the string represents 12:50:30 (50 and half minutes, format "HHMM.mmm", because "a decimal fraction may be added to the lowest order time element present")

if partial minutes are not supported by Python as stated in the docs, a ValueError should be raised.

Affected are versions 3.10+.

CPython versions tested on:

3.12

Operating systems tested on:

Linux

Linked PRs

pganssle commented 7 months ago

if partial minutes are not supported by Python as stated in the docs, a ValueError should be raised.

Fractional hours and minutes should not be supported. We should change the time.fromisoformat docs to reflect that and raise a ValueError in this case.

The reason why they are not supported is that we decided that a string like T12:00.50 is much more likely to be a typo for something like T12:00:50 than to be an actual fractional hour or minute, because this is a particularly obscure feature of ISO-8601.

@xitop How did you discover this? Were you using something that actually generates a string like that, or was this an attempt to find bugs? I'm curious to know if my reasoning about no one really using these features is correct.

xitop commented 7 months ago

@xitop How did you discover this?

Pure chance. I was working on a software processing time intervals with a parser accepting various formats. I read the .fromisoformat() docs and used such string in a unit test as an example of incorrect input. As you wrote, it looks like a typo, so it is likely that the parser encounters input like that.