Home > Back-end >  how to calculate date range correctly using arrow in python
how to calculate date range correctly using arrow in python

Time:05-17

I have the small snippet of codes below, I am trying to calculate the number of days between today and yesterday using arrow and make sure the result is accurate.

import arrow

TODAY = arrow.now()

YESTERDAY = arrow.now().shift(days=-1)

result = TODAY - YESTERDAY

print("result: ", result)
print("number of days: ", result.days)
print("TODAY: ", TODAY)
print("YESTERDAY: ", YESTERDAY)

here is the result that i am getting:

result:  23:59:59.999912
number of days:  0     # this is because the result is not 24 but 23:59 instead... 
TODAY:  2022-05-16T11:54:03.332408 00:00
YEST:  2022-05-15T11:54:03.332496 00:00

Is there a better way that i am missing on how to achieve the above using arrow specifically?

CodePudding user response:

Try about doing TODAY.shift(days=-1) instead of arrow.now().shift(days=-1). This way your dates will be exactly 1 day apart, no matter how long execution of statements took.

CodePudding user response:

I ran it several times on my system and it always came up with

result:  1 day, 0:00:00
number of days:  1
TODAY:  2022-05-16T07:15:14.513011-05:00
YESTERDAY:  2022-05-15T07:15:14.513011-05:00

Does it get better on your machine if you change

YESTERDAY = arrow.now().shift(days=-1)

to this?

YESTERDAY = TODAY.shift(days=-1)
  • Related