Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculating difference in time between two Time objects

Let's say I create two time objects from my user model:

created = u.created_at
updated = u.updated_at

How do I calculate the difference in terms of hours between the two time objects?

hours = created - updated

I'd like to wrap this in a method and extend the Time class. I find it hard to believe I'd need to extend it, but I can't seem to find a native method that handles calculating elapsed time using different time units.

like image 265
keruilin Avatar asked Jul 22 '11 00:07

keruilin


People also ask

How do you find the time difference between two times?

To calculate the number of hours between two times: Subtract the starting time from the ending time. Do you have any seconds or minutes after the subtraction? If so: Take seconds, divide them by 60, and add the result to the minutes.

How can you find the difference in time between two datetime objects time_1 and time_2?

Subtracting the later time from the first time difference = later_time - first_time creates a datetime object that only holds the difference. In the example above it is 0 minutes, 8 seconds and 562000 microseconds.

How do I calculate the time difference between two times in python?

timedelta() method. To find the difference between two dates in Python, one can use the timedelta class which is present in the datetime library. The timedelta class stores the difference between two datetime objects.


1 Answers

This should work:

hours = ((created - updated) / 1.hour).round

Related question: Rails Time difference in hours

like image 123
Stephen Provis Avatar answered Oct 13 '22 12:10

Stephen Provis