Converting date into hours

Rohita Khatiwada picture Rohita Khatiwada · Apr 10, 2011 · Viewed 19.7k times · Source

I want to find time difference between two date and then compare the difference time in hours. Something like this,

StartTime = 2011-03-10 15:45:48 EndTime = 2011-03-10 18:04:00

And then find the difference as, timeDifference = abs(StartTime - EndTime) And then I need to compare the results as, If timeDifference > 6 hours ...

When I use this method, the results I got was is in time format, how should I change time format into hours in python?

Thank you,

Answer

Mark Longair picture Mark Longair · Apr 10, 2011

Let's assume that you have your two dates and times as datetime objects (see datetime.datetime):

>>> import datetime
>>> start_time = datetime.datetime(2011,3,10,15,45,48)
>>> end_time = datetime.datetime(2011,3,10,18,4,0)

Subtracting one datetime from another gives you a timedelta object, and you can use abs to ensure the time difference is positive:

>>> start_time - end_time
datetime.timedelta(-1, 78108)
>>> abs(start_time - end_time)
datetime.timedelta(0, 8292)

Now, to convert the seconds difference from a timedelta into hours, just divide by 3600:

>>> hours_difference = abs(start_time - end_time).total_seconds() / 3600.0
>>> hours_difference
2.3033333333333332

Note that the total_seconds() method was introduced in Python 2.7, so if you want that on an earlier version, you'll need to calculate it yourself from .days and .seconds as in this answer

Update: Jochen Ritzel points out in a comment below that if it's just the comparison with a number of hours that you're interested in, rather that the raw value, you can do that more easily with:

abs(start_time - end_time) > timedelta(hours=6)