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.
This should be amenable to regex, since it seems very regular. It may have days specified at the beginning, or microseconds at the end. But its very... regular:
Note, take care using the
re.VERBOSEflag with spaces, they are ignored outside of specific cases unless you escape them. But I do think it is more readable this way.Examples of how to use this:
You could also just write the function to convert the string to timedelta object like so:
Here's a more rigorous test (still not very rigorous):