Difference between timestamps in Arrow

16.9k views Asked by At

How would I get Arrow to return the difference in hours between two timestamps?

Here's what I have:

difference = arrow.now() - arrow.get(p.create_time())
print(difference.hour)

p.create_time() being the timestamp of the create time of a currently running process.

Returns:

AttributeError: 'datetime.timedelta' object has no attribute 'hour'

Edit: I don't want the total time in all three formats, I want it as a remainder eg. "3 days, 4 hours, 36 minutes" not "3 days, 72 hours, 4596 minutes"

1

There are 1 answers

0
OShadmon On BEST ANSWER

Given 2 dates that are formatted from a string to arrow type.

>>> date_1 = arrow.get('2015-12-23 18:40:48','YYYY-MM-DD HH:mm:ss')
>>> date_2 = arrow.get('2017-11-15 13:18:20','YYYY-MM-DD HH:mm:ss')
>>> diff = date_2 - date_1

The difference is a datetime.timedelta data type.

>>> print type(diff)
<type 'datetime.timedelta'>

And results in:

>>> print diff
692 days, 18:37:32

To get it formatted such that you would have D days, H hours, M minutes, S seconds you would get the days separately, and then using divmod function get the other information.

>>> days = diff.days # Get Day 
>>> hours,remainder = divmod(diff.seconds,3600) # Get Hour 
>>> minutes,seconds = divmod(remainder,60) # Get Minute & Second 

The result would be:

>>> print days, " Days, ", hours, " Hours, ", minutes, " Minutes, ", seconds, " Second"
692  Days,  18  Hours,  37  Minutes,  32  Second