Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert a timedelta object into a datetime object

People also ask

How do I change the Timedelta to datetime?

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.

How do I convert a date to a datetime object?

You can use the datetime module's combine method to combine a date and a time to create a datetime object. If you have a date object and not a time object, you can initialize the time object to minimum using the datetime object(minimum time means midnight).

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.


It doesn't make sense to convert a timedelta into a datetime, but it does make sense to pick an initial or starting datetime and add or subtract a timedelta from that.

>>> import datetime
>>> today = datetime.datetime.today()
>>> today
datetime.datetime(2010, 3, 9, 18, 25, 19, 474362)
>>> today + datetime.timedelta(days=1)
datetime.datetime(2010, 3, 10, 18, 25, 19, 474362)

Since a datetime represents a time within a single day, your timedelta should be less than 24 hours (86400 seconds), even though timedeltas are not subject to this constraint.

import datetime

seconds = 86399
td = datetime.timedelta(seconds=seconds)
print(td)
dt = datetime.datetime.strptime(str(td), "%H:%M:%S")
print(dt)

23:59:59
1900-01-01 23:59:59

If you don't want a default date and know the date of your timedelta:

date = "05/15/2020"
dt2 = datetime.datetime.strptime("{} {}".format(date, td), "%m/%d/%Y %H:%M:%S")
print(dt2)

2020-05-15 23:59:59