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,
Let’s assume that you have your two dates and times as
datetimeobjects (see datetime.datetime):Subtracting one
datetimefrom another gives you atimedeltaobject, and you can useabsto ensure the time difference is positive:Now, to convert the seconds difference from a timedelta into hours, just divide by 3600:
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.daysand.secondsas in this answerUpdate: 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: