Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert a timedelta to a string and back again

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?

like image 704
Kurt Peek Avatar asked Nov 25 '16 14:11

Kurt Peek


People also ask

How do I convert Timedelta?

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)

How do you convert Timedelta to seconds?

To get the Total seconds in the duration from the Timedelta object, use the timedelta. total_seconds() method.

How do I convert Timedelta to minutes?

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.

How do you convert a string to a Timedelta?

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.


1 Answers

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)
like image 197
SparkAndShine Avatar answered Oct 26 '22 06:10

SparkAndShine