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.
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.
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.
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.
This should work:
hours = ((created - updated) / 1.hour).round
Related question: Rails Time difference in hours
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With