JamesHudson81
JamesHudson81

Reputation: 2273

Obtain the index of a list of dates that is the closest to a given date

I have the following date:

date=np.datetime64 (2019-12-15)

then I have a list of np.datetime64 dates:

['2018-01-01','2019-01-01','2019-04-12','2019-12-01']

I would like to obtain the index from the list which is closest to my date.

The desired output would be 3 which is the position of the list of dates closer to my date.

I am not able to provide an example given I dont know how to test my issue.

I can only think of an assert.AlmostEqual but I am not sure on how to reflect it on an example.

Upvotes: 1

Views: 985

Answers (2)

blackbrandt
blackbrandt

Reputation: 2095

According to the datetime documentation, you can calculate timedeltas by simply subtracting the dates.

#Set date
date=np.datetime64 ('2019-12-15')


#Create list of strings holding date values
l = ['2018-01-01','2019-01-01','2019-04-12','2019-12-01']

#Convert strings to numpy dates 
l = [numpy.datetime64(x) for x in l]

#For each value in date list, subtract from start date. 
delta = [abs(x - date) for x in l]

#Set minimum index (see link below)
idx = np.argmin(d)


This will output 3.

Min index code obtained from here

Upvotes: 0

michcio1234
michcio1234

Reputation: 1838

Express your list as a numpy array and just find the index of the smallest difference using np.argmin:

import numpy as np

date = np.datetime64('2019-12-15')
array = np.array(['2018-01-01','2019-01-01','2019-04-12','2019-12-01'],
                 dtype=np.datetime64)

result = np.argmin(np.abs(array - date))

Upvotes: 5

Related Questions