pythondatetimeserializationtimedeltaelapsedtime

Convert string that was originally a `timedelta` back into a `timedelta` object in Python


I have strings which were originally produced from timedelta objects like so: print(f'{my_delta}').

I have many of these statements logged (e.g. "12:21:00", "1 day, 0:53:00", "2 days, 9:28:00") and I simply want to parse these logged statements to convert back to timedelta objects. Is this possible with the datetime library?

The strings were literally produced from just printing timedelta objects, but I cannot seem to convert back by using timedelta(my_string). Wondering if there is a standard way of doing this that I am missing.


Solution

  • As others have noted emphatically, the datetime library does not seem to support this functionality.

    Here's a one-liner that uses regex:

    >>> from datetime import timedelta
    >>> import re
    >>> 
    >>> str_to_dlt = lambda t: timedelta(days=int((m:=re.match(r'((\d+)\sdays?,\s*)?(\d{1,2}):(\d{2}):(\d{2})', t))[2] or 0), hours=int(m[3]), minutes=int(m[4]), seconds=int(m[5]))
    

    Printing the timedelta returns the original string it was supplied:

    >>> print(str_to_dlt('5:11:13'))
    5:11:13
    >>> 
    >>> print(str_to_dlt('1 day, 5:11:13'))
    1 day, 5:11:13
    >>> 
    >>> print(str_to_dlt('2 days, 5:11:13'))
    2 days, 5:11:13