views:

100

answers:

2

Why I can't subtract two time object? 12:00 - 11:00 = 1:00


from datetime import time
time(12,00) - time(11,00) # -> timedelta(hours=1)

Actually

TypeError: unsupported operand type(s) for -: 'datetime.time' and 'datetime.time'
+3  A: 

The time objects have no date, so (e.g.) the 12:00 might be (say) on a Wed and the 11:00 on the preceding Tue, making the difference 25 hours, not one (any multiple of 24 might be added or subtracted). If you know they're actually on the same date, just apply any arbitrary date to each of them (making two datetime objects) and then you'll be able to subtract them. E.g.:

import datetime

def timedif(t1, t2):
  td = datetime.date.today()
  return datetime.datetime.combine(td, t1) - datetime.datetime.combine(td, t1)
Alex Martelli
yes, this is a trick... but I continue to understand why <pre>__sub__</pre> is not implemented: it is obvious that the two time refer to same day, otherwise I should have used datetime.datetime.For example datasheet software do this (excel)
wiso
Maybe obvious to you, but not to everyone. It's easier to not support it now, allow support for it in the future, and not have to live with a possibly-bad choice now.
Roger Pate
This is kind of related to how you cannot modify a datetime.time() object with a datetime.timedelta() object. As Alex says, not having a date component means that you do not know if they are on the same day. Similarly, if you add/subtract a timedelta, it may push the time onto another day (overflow), and there is no way to know this.
Matthew Schinckel
A: 

You can get your desired result by

t1 = time(12, 0)
t2 = time(11, 0)
td = timedelta(hours=t1.hour-t2.hour, minutes=t1.minute-t2.minute)
Tor Valamo
ok, of course, but I want to understand why the __sub__ method is not implemented
wiso