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?
问题:
回答1:
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.
回答2:
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)
回答3:
You could transform both into timedelta objects and subtract these from each other, which will take care to of the carry-overs. For example:
>>> import datetime as dt
>>> t1 = dt.time(23, 5, 5, 5)
>>> t2 = dt.time(10, 5, 5, 5)
>>> dt1 = dt.timedelta(hours=t1.hour, minutes=t1.minute, seconds=t1.second, microseconds=t1.microsecond)
>>> dt2 = dt.timedelta(hours=t2.hour, minutes=t2.minute, seconds=t2.second, microseconds=t2.microsecond)
>>> print(dt1-dt2)
13:00:00
>>> print(dt2-dt1)
-1 day, 11:00:00
>>> print(abs(dt2-dt1))
13:00:00
Negative timedelta objects in Python get a negative day field, with the other fields positive. You could check beforehand: comparison works on both time objects and timedelta objects:
>>> dt2 < dt1
True
>>> t2 < t1
True
回答4:
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.
回答5:
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
回答6:
Retrieve the times in milliseconds and then do the subtraction.
回答7:
Environment.TickCount seems to work well if you need something quick.
int start = Environment.TickCount
...DoSomething()
int elapsedtime = Environment.TickCount - start
Jon