How to convert a timedelta object into a datetime object

Question:

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?

Asked By: olamundo

||

Answers:

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)
Answered By: Roger Pate

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)
)
Answered By: sadpanduar

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
Answered By: Bill Gale

Improving @sadpanduar answer with example on converting one column in pandas.DataFrame:

from datetime import timedelta
import time

def seconds_to_datetime(seconds, format='%Y-%m-%d %H:%M:%S'):
    td = timedelta(seconds=seconds)
    time_obj = time.gmtime(td.total_seconds())
    return time.strftime(format, time_obj)
df = pd.read_csv(CSV_PATH)
df['TIMESTAMP_COLUMN'] = df['TIMESTAMP_COLUMN'].apply(seconds_to_datetime)
Answered By: Muhammad Yasirroni
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.