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?
There are two different ways of doing this conversion: the first one you divide the total_seconds() by the number of seconds in a minute, which is 60. the second approach, you divide the timedelta object by timedelta(minutes=1)
To get the Total seconds in the duration from the Timedelta object, use the timedelta. total_seconds() method.
The timedelta class stores the difference between two datetime objects. To find the difference between two dates in form of minutes, the attribute seconds of timedelta object can be used which can be further divided by 60 to convert to minutes.
Convert String to TimeDelta We can even convert time in string format to datetime by using the strptime() function and then extracting the timedelta information using the timedelta module. We can use the repr(td) to print the timedelta as a constructor with attributes in a string format.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With