Skip to content Skip to sidebar Skip to footer

Find Closest Past Date In List Of Dates

I'm trying to find the closest past date in a list of dates to the current date. I've found several examples of searching for the closest date in a list but all these allow for the

Solution 1:

Using min with two keys would be one way:

from datetime import datetime

now = datetime.now()
min(datelist, key=lambda x: (x>now, abs(x-now)) )

Output:

datetime.datetime(2020, 1, 31, 0, 0)

Solution 2:

You can use np.searchsorted as you already attempted with its side arg set as right, so that it considers only the ones before it or same as itself. Now, since by its definition searchsorted gets us the index of position of the date to be searched in the larger sorted array, we need to subtract 1 to get the closest one before it.

Hence, simply do -

datelist[np.searchsorted(datelist, datetime.datetime.now(), side='right')-1]

Sample runs -

In [48]: datelist = [datetime.datetime(2020, 2, 5, 0, 0),
    ...:  datetime.datetime(2020, 2, 8, 0, 0),
    ...:  datetime.datetime(2020, 2, 12, 0, 0),
    ...:  datetime.datetime(2020, 2, 20, 0, 0)]

In [49]: datelist[np.searchsorted(datelist, datetime.datetime(2020, 2, 11, 0, 0), side='right')-1]
Out[49]: datetime.datetime(2020, 2, 8, 0, 0)

In [50]: datelist[np.searchsorted(datelist, datetime.datetime(2020, 2, 7, 0, 0), side='right')-1]
Out[50]: datetime.datetime(2020, 2, 5, 0, 0)

Post a Comment for "Find Closest Past Date In List Of Dates"