Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between timestamps in Arrow

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"

like image 773
Sweepyoface Avatar asked Dec 24 '16 02:12

Sweepyoface


People also ask

What is timestamp difference?

{fn TIMESTAMPDIFF(interval,startDate,endDate)} returns the difference between the starting and ending timestamps (startDate minus endDate) for the specified date part interval (seconds, days, weeks, and so on). The function returns an INTEGER value representing the number of intervals between the two timestamps.

How do you find the difference between two timestamps in seconds?

If you'd like to calculate the difference between the timestamps in seconds, multiply the decimal difference in days by the number of seconds in a day, which equals 24 * 60 * 60 = 86400 , or the product of the number of hours in a day, the number of minutes in an hour, and the number of seconds in a minute.

How do you use arrows in Python?

Arrow is a Python module for working with date and time. It offers a sensible and human-friendly approach to creating, manipulating, formatting and converting dates, times and timestamps. It allows easy creation of date and time instances with timezone awareness.

What is Arrow Python?

Arrow is a flexible Python library designed to create, format, manipulate, and convert dates, time, and timestamps in a sensible and human-friendly manner. It provides an intelligent module API that allows dealing with dates and times with a few code lines and imports.


1 Answers

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
like image 103
OShadmon Avatar answered Sep 16 '22 18:09

OShadmon