What is the simplest way to find the difference be

2020-08-10 19:11发布

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?

7条回答
forever°为你锁心
2楼-- · 2020-08-10 19:41

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
查看更多
爷的心禁止访问
3楼-- · 2020-08-10 19:45

Retrieve the times in milliseconds and then do the subtraction.

查看更多
We Are One
4楼-- · 2020-08-10 19:46

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)
查看更多
叼着烟拽天下
5楼-- · 2020-08-10 19:55

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.

查看更多
神经病院院长
6楼-- · 2020-08-10 20:01

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.

查看更多
爷的心禁止访问
7楼-- · 2020-08-10 20:02

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

查看更多
登录 后发表回答