pyPN
pyPN

Reputation: 105

Python: Calculate number of days between two days

I have two arrays, reference array and target array. Each array has day of year (DOY) information and I am trying to find the difference in actual number of days between the two. Here is the code,

import numpy as np

array_ref = np.array([[362,284],[89,360]])
array_ref
array([[362, 284],
       [ 89, 360]])

array_n = np.array([[2, 365], [194, 10]])
array_n
array([[  2, 365],
       [194,  10]])

The absolute difference gives this,

print(abs(array_ref-array_n))
[[360  81]
 [105 350]]

However, I am trying to achieve this,

[[5, 81]
 [105, 15]]

I am not sure if I have to use any datetime or timedelta function or if there is a more simpler way to achieve this. Thanks for your help.

Upvotes: 1

Views: 179

Answers (1)

ALollz
ALollz

Reputation: 59579

With remainder division.

(array_n-array_ref)%365
array([[  5,  81],
       [105,  15]], dtype=int32)

In general, you may want to check which subtraction is closer:

np.minimum((array_ref-array_n)%365, (array_n-array_ref)%365)
array([[  5,  81],
       [105,  15]], dtype=int32)

Though this will clearly fail to take leap years into account.

Upvotes: 1

Related Questions