Adding timedelta object to datetime

2.9k Views Asked by At

My timedelta object looks like this: txdelta = 00:30:00. I want to add it to a datetime object but it consistently isn't working:

from datetime import datetime, date, time, timedelta
localdt = datetime.combine(datetime.strptime('2015-06-18', '%Y-%m-%d').date(),
(23:35:02+timedelta(txdelta)).time())

Note that the 23:35:02 is already a datetime object. I get this error message:

TypeError: unsupported type for timedelta days component: datetime.timedelta

What am I doing wrong?

1

There are 1 best solutions below

0
On BEST ANSWER

The way you create your time object is strange. I strongly advice you to declare it this way if you're not used to it:

txdelta = timedelta(minutes=30)
tdelta = time(hour=1, minute=35, second=2)

If I got it well you tried to combine a date, a time and a timedelta. The full code below should do the trick:

from datetime import datetime, date, time, timedelta

txdelta = timedelta(minutes=30)
tdelta = time(hour=1, minute=35, second=2)
localdt = datetime.combine(datetime.strptime('2015-06-18', '%Y-%m-%d').date(), tdelta) + txdelta

print(localdt)

Basically, you combine a datetime object with a time one, and you simply add the timedelta object afterwards.

The output is:

2015-06-18 02:05:02