How to get the number of seconds between two dates with arrow?

1.8k Views Asked by At

I use arrow to handle dates and discovered that I do not know how to get natively the number of seconds between two dates:

>>> import arrow
>>> first = arrow.get('2019-03-06')
>>> second = arrow.get('2019-02-06')
>>> (first-second).days
28
>>> (first-second).seconds
0

From the example above it looks like .days gives the expected output, but .seconds rather gives the number of seconds there are "at the seconds level", that is when looking exclusively at seconds. This would mean that the maximum number is 60.

This is not true, however:

>>> (arrow.now()-first).seconds
70223

70000 seconds is approximately 19 hours, which would be the correct number of hours between last midnight (start of today) and now (about 20:30).

So I am lost at what .seconds actually provides.

2

There are 2 best solutions below

0
On

The seconds property only reflects the difference between first and second if they're within one day. If the days are more than 1 day then the days property get increment by one and the seconds property get reset to zero. If you want to get the total seconds between them, then call the total_seconds() method of the timedelta. See below for the differences

import arrow

first = arrow.get('2019-03-06 02:00:00')
second = arrow.get('2019-03-05 01:00:00')
d0 = first - second
d1 = d0.days
d2 = d0.seconds
d3 = d0.total_seconds()
print('total days: {}'.format(d1))
print('seconds within day: {}'.format(d2))
print('total seconds: {}'.format(d3))

# total days: 1
# seconds within day: 3600
# total seconds: 90000.0
0
On

Documentation for datetime

.seconds is the number of seconds within a day

.total_seconds() is the entire timedelta converted to seconds

For example:

first = arrow.get('2019-03-06 02:00:00')
second = arrow.get('2019-03-05 01:00:00')

(first - second).seconds
> 3600

(first - second).total_seconds()
> 90000.0

So for less than a day difference .seconds & .total_seconds() would be identical.