How to convert a timedelta to a string and back again

Kurt Peek picture Kurt Peek · Nov 25, 2016 · Viewed 9.3k times · Source

Dateutil's timedelta object appears to have a custom __str__ method:

In [1]: from datetime import timedelta

In [2]: td = timedelta(hours=2)

In [3]: str(td)
Out[3]: '2:00:00'

What I'd like to do is re-create a timedelta object from its string representation. As far as I can tell, however, the datetime.parser.parse method will always return a datetime.datetime object (cf. https://dateutil.readthedocs.io/en/stable/parser.html):

In [4]: import dateutil.parser

In [5]: dateutil.parser.parse(str(td))
Out[5]: datetime.datetime(2016, 11, 25, 2, 0)

The only way I see now to do this is to, in the parlance of Convert a timedelta to days, hours and minutes, 'bust out some nauseatingly simple (but verbose) mathematics' to obtain the seconds, minutes, hours, etc., and pass these back to the __init__ of a new timedelta. Or is there perhaps a simpler way?

Answer

SparkAndShine picture SparkAndShine · Nov 25, 2016

Use datetime.strptime to convert a string to timedelta.

import datetime

td = datetime.timedelta(hours=2)

# timedelta to string
s = str(td) # 2:00:00

# string to timedelta
t = datetime.datetime.strptime(s,"%H:%M:%S")
td2 = datetime.timedelta(hours=t.hour, minutes=t.minute, seconds=t.second)