35

I have two date time objects like this

a = first date time object
b = second date time object

And then

c = a - b

Now I want to compare c and check if the difference was greater than 3 hours, so I have a time object called three_hours

three_hours = datetime.time(3,0)
if c >= three_hours:
     #do stuff

but I get an error saying cannot compare datetime.teimdelta to datetime.time

My question is different as I also want to then compare the subtracted time, not just get the difference!!

How can I convert them to the correct formats so I can check if 3 hours has passed?

Thanks for the help

spen123
  • 3,464
  • 11
  • 39
  • 52
  • http://stackoverflow.com/questions/3426870/calculating-time-difference – dsgdfg Aug 25 '15 at 18:41
  • The value of datetime.timedelta object d can be converted to hours with d.days*24 + (d.seconds + d.microseconds*10**6)/3600 –  Aug 26 '15 at 02:13

3 Answers3

51

When you subtract two datetime objects in python, you get a datetime.timedelta object. You can then get the total_seconds() for that timedelta object and check if that is greater than 3*3600 , which is the number of seconds for 3 hours. Example -

>>> a = datetime.datetime.now()
>>> b = datetime.datetime(2015,8,25,0,0,0,0)
>>> c = a - b
>>> c.total_seconds()
87062.729491
>>> c.total_seconds() > 3*3600
True
Anand S Kumar
  • 88,551
  • 18
  • 188
  • 176
11

You can also just compare to another timedelta object

import datetime
if c >= datetime.timedelta(hours=3):
   #do something
NightShadeQueen
  • 3,284
  • 3
  • 24
  • 37
2

You can do this

three_hours = 3600*3 # in seconds

if c.total_seconds() >= three_hours:
    # do stuff
YOBA
  • 2,759
  • 1
  • 14
  • 29