47

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?

6 Answers 6

53

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)
Sign up to request clarification or add additional context in comments.

4 Comments

+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.
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
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
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.
3

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

Comments

2

I share your pain bro

import datetime
from dateutil.relativedelta import relativedelta

# Both variables datetime
birthday = datetime.datetime(2000, 5, 24)
today = datetime.datetime.today()

# Time you've been alive in timedelta format
time_alive = today - birthday
print(time_alive)
>>> 8609 days, 18:47:53.341251

# Get only the time to concatenate later
hours = (datetime.datetime.min + time_alive).time()
print(hours)
>>> 18:47:53.341251

# Date that you've been alive
age = datetime.datetime.combine(datetime.datetime.fromordinal(time_alive.days) - relativedelta(years=1), hours)
print(age)
>>> 0023-07-27 18:47:53.341251

Comments

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)
)

1 Comment

that's a time object not a datetime object ( as asked )
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 Comment

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.
-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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.