From:
http://docs.python.org/py3k/library/datetime.html#timedelta-objects
A timedelta object represents a duration, the difference between two dates or times.
So why i get error with this:
>>> from datetime import datetime, timedelta, time
>>> datetime.now() + timedelta(hours=12)
datetime.datetime(2012, 9, 17, 6, 24, 9, 635862)
>>> datetime.now().date() + timedelta(hours=12)
datetime.date(2012, 9, 16)
>>> datetime.now().time() + timedelta(hours=12)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'datetime.time' and 'datetime.timedelta'
How would this work?
datetime.datetime.now().time()
returns only hours, minutes, seconds and so on, there is no date information what.time()
returns, only time.Then, what should
18:00:00 + 8 hours
return?There's not answer to that question, and that's why you can't add a time and a timedelta.
In other words:
A datetime.time object can be split into separate integer components that you can add to. No need for timedelta eg:
datetime.time
objects do not support addition withdatetime.timedelta
s.There is one natural definition though, clock arithmetic. You could compute it like this:
dt.datetime.combine(...)
lifts the datetime.timet
to adatetime.datetime
object, the delta is then added, and the result is dropped back down to adatetime.time
object.Here is a function that adds a
time
to atimedelta
:This will provide the expected result so long as you don't add times in a way that crosses a midnight boundary.