How to convert a timedelta object into a datetime object

62,931

Solution 1

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

Solution 2

I found that I could take the .total_seconds() and use that to create a new time object (or datetime object if needed).

import time
import datetime

start_dt_obj = datetime.datetime.fromtimestamp(start_timestamp)
stop_dt_obj = datetime.datetime.fromtimestamp(stop_timestamp)
delta = stop_dt_obj - start_dt_obj

delta_as_time_obj = time.gmtime(delta.total_seconds())

This allows you to do something like:

print('The duration was {0}'.format(
    time.strftime('%H:%M', delta_as_time_obj)
)
Share:
62,931
olamundo
Author by

olamundo

Updated on February 16, 2022

Comments

  • olamundo
    olamundo about 2 years

    What is the proper way to convert a timedelta object into a datetime object?

    I immediately think of something like datetime(0)+deltaObj, but that's not very nice... Isn't there a toDateTime() function or something of the sort?