Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the simplest way to find the difference between 2 times in python?

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?

like image 522
airportyh Avatar asked Sep 09 '08 00:09

airportyh


1 Answers

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)
like image 139
Blair Conrad Avatar answered Oct 22 '22 10:10

Blair Conrad