Adding timedelta to a datetime.time

• 2 min read

One of Python's strengths is its exhaustive library. And date and time management is an integral part of this, provided by the datetime.

Logic suggests that timedelta. That is code like this would produce an error:

>>> from datetime import datetime, date, time, timedelta
>>> dt1 = datetime.now()
>>> td1 = timedelta(hours=1)
>>> dt1 + td1
datetime.datetime(2014, 6, 26, 15, 38, 27, 149200) # OK
>>> dt1.time()+td1
Traceback (most recent call last):
  File "", line 1, in 
TypeError: unsupported operand type(s) for +: 'datetime.time' and 'datetime.timedelta'

So how do you add (or subtract) a timedelta(or date) object? It turns out that a slightly convoluted way exists. Given a time object t1 and timedelta object td1, the following code does the trick.

>>> (datetime.combine(datetime.now().date(), t1)+td1).time()
datetime.time(15, 40, 55, 672503)

There is probably a shorter and better way to accomplish, but at the moment this is what I could come up with.