views:

943

answers:

7

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?

A: 

It 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

pkaeding
+3  A: 

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).

chryss
chryss: You could seriously do well with an example here.
Arafangion
A: 

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.

Jason Etheridge
Note that this solution doesn't preserve sign. Also,delta_ms = abs(t1_ms - t2_ms) is a little easier to understand and saves at least a subtraction.
Blair Conrad
doesn't work if t1_ms is before midnight and t2_ms is after midnight
Mr Fooz
Shouldn't it be * 1000000? Since 1 s = 1000000 µs.
Paggas
+4  A: 

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)
Blair Conrad
+3  A: 

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.

Girish
A: 

Retrieve the times in milliseconds and then do the subtraction.

Joshua
A: 

Environment.TickCount seems to work well if you need something quick.

int start = Environment.TickCount

...DoSomething()

int elapsedtime = Environment.TickCount - start

Jon