I have 2 time values which have the type datetime.time. I want to find their difference. The obvious thing to do is t1 - t2, but this doesn't work. It works for objects of type datetime.datetime but not for datetime.time. So what is the best way to do this?
views:
943answers:
7It seems that this isn't supported, since there wouldn't be a good way to deal with overflows in datetime.time. I know this isn't an answer directly, but maybe someone with more python experience than me can take this a little further. For more info, see this: http://bugs.python.org/issue3250
You could transform both into timedelta objects and subtract these from each other, taking care to handle carry-overs correctly (from sec to min etc).
Firstly, note that a datetime.time is a time of day, independent of a given day, and so the different between any two datetime.time values is going to be less than 24 hours.
One approach is to convert both datetime.time values into comparable values (such as milliseconds), and find the difference.
t1, t2 = datetime.time(...), datetime.time(...)
t1_ms = (t1.hour*60*60 + t1.minute*60 + t1.second)*1000 + t1.microsecond
t2_ms = (t2.hour*60*60 + t2.minute*60 + t2.second)*1000 + t2.microsecond
delta_ms = max([t1_ms, t2_ms]) - min([t1_ms, t2_ms])
It's a little lame, but it works.
Also a little silly, but you could try picking an arbitrary day and embedding each time in it, using datetime.datetime.combine
, then subtracting:
>>> import datetime
>>> t1 = datetime.time(2,3,4)
>>> t2 = datetime.time(18,20,59)
>>> dummydate = datetime.date(2000,1,1)
>>> datetime.datetime.combine(dummydate,t2) - datetime.datetime.combine(dummydate,t1)
datetime.timedelta(0, 58675)
Python has pytz (http://pytz.sourceforge.net) module which can be used for arithmetic of 'time' objects. It takes care of DST offsets as well. The above page has a number of examples that illustrate the usage of pytz.