Skip to content

string representation of a timedelta objects cannot be read by time class #135176

Closed as duplicate
@lenneman

Description

@lenneman

Feature or enhancement

Proposal:

The __str__ method of the datetime.timediff class returns a string representation of a time difference in days, hours, minutes, seconds, microseconds. The representation of minutes and seconds is with a leading zero, which is fine. But the hours is not with a leading zero.
Example:

>>> tstart = datetime.now()
...
>>> tend = datetime.now()
>>> tend - tstart
datetime.timedelta(seconds=5, microseconds=737300)
>>> str(tend - tstart)
'0:00:05.737300'

The problem is now that the method fromisoformat of the datetime.time class does not recognize this string as a valid iso-format string because of the missing leading zero:

>>> str(tend-tstart)
'0:00:05.737300'
>>> time.fromisoformat(str(tend-tstart))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: Invalid isoformat string: '0:00:05.737300'

adding a leading zero works:

>>> time.fromisoformat('00:00:05.737300')
datetime.time(0, 0, 5, 737300)
>>> str(time.fromisoformat('00:00:05.737300'))
'00:00:05.737300'

interestingly the __str__ method of time has a leading zero for the hours.

So the __str__ method of timedelta shall add a leading zero as well to be conform to the ISO format.

Has this already been discussed elsewhere?

This is a minor feature, which does not need previous discussion elsewhere

Links to previous discussion of this feature:

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    type-featureA feature request or enhancement

    Projects

    Status

    Done

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions