42

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?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
olamundo
  • 23,991
  • 34
  • 108
  • 149

5 Answers5

49

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)
  • 20
    +1: Epochal dates. March 8th is my daughter's birthday, that's a better epochal date than March 9th. Unix folks like Jan 1, 1970. Don't know why, that's not my daughter's birthday. – S.Lott Mar 10 '10 at 02:13
  • 4
    I am trying to do this: `period['start_date'] = (self.start_date + timedelta(days=roundtrip_component.day-1)).strftime("%d/%m/%Y")`, and I get this error: `TypeError: must be str, not datetime.timedelta`. So I guess in this case it makes sense to change the type **timedelta** to **date** – HuLu ViCa Nov 08 '18 at 23:07
  • 1
    It makes a lot of sense to convert it I have StartTime and EndTime of trips which are both in time delta format and I am trying to figure out why and how to put them in time format. On the phpmyadmin is normal time and when I download it from a tunnel and use it in python, they are both timedelta and I can not do anything with them – Georgi Ivanov Dimitrov Apr 10 '19 at 11:53
  • 1
    Not helpful. Do not redefine a question and then answer it. I have a timedelta I need to get into a datetime so I can format it. – Bill Gale May 20 '20 at 13:22
2

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
Bill Gale
  • 1,238
  • 1
  • 14
  • 14
1

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)
)
sadpanduar
  • 84
  • 1
  • 6
0
    import datetime`enter code here
    lastDownloadedDate = datetime.date(2022,8,4)
    print('lastDownloadedDate: ', lastDownloadedDate)
    fdate = lastDownloadedDate + datetime.timedelta(days=1)
    fdate = datetime.datetime.strptime(str(fdate), "%Y-%m-%d")
    fdate = datetime.date(fdate.year, fdate.month, fdate.day)
    print('fdate: ', dt3)`
  • 1
    Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Aug 05 '22 at 15:53
-1

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)
Muhammad Yasirroni
  • 1,512
  • 12
  • 22