You can't subtract time
instances, because there's no definitive ordering to them; what's the difference between 12.00 and 13.00? An hour? What if I now tell you I mean 12.00 yesterday and 13.00 tomorrow? Hence the error:
>>> from datetime import date, time, datetime
>>> t1 = time(12, 00)
>>> t2 = time(13, 00)
>>> t1 - t2
Traceback (most recent call last):
File "<pyshell#3>", line 1, in <module>
t1 - t2
TypeError: unsupported operand type(s) for -: 'datetime.time' and 'datetime.time'
You need to know what day the times occur on to calculate the difference. You need to convert them to datetime
objects by combining them with the appropriate date
:
>>> dt1 = datetime.combine(date(2015, 7, 14), t1)
>>> dt2 = datetime.combine(date(2015, 7, 16), t2)
Now you can subtract them:
>>> dt2 - dt1
datetime.timedelta(2, 3600) # two days, 3,600 seconds
If they're on the same day (or you're assuming they are), it generally* doesn't matter which day, so you can do e.g.
>>> datetime.combine(date.today(), t2) - datetime.combine(date.today(), t1)
datetime.timedelta(0, 3600) # one hour
* (i.e. ignoring changing clocks, leap seconds, ...)