I have an array of datetime objects, and I would like to find which element in the array is the closest to a given date (e.g datetime.datetime(2014,12,16)
)
This post shows how to find the nearest date which is not before the given date. How can I alter this code so that it can return dates that are before a given date?
For example, if the array housed elements datetime.datetime(2014,12,10)
and datetime.datetime(2014,12,28)
, the former item should be returned because it is closest to datetime.datetime(2014,12,16)
in absolute value.
Finding the future closest date to today in Excel 1. Select the blank cell B2, copy and paste formula =MIN(IF(A2:A18>TODAY(),A2:A18)) into the Formula Bar, and then press Ctrl + Shift + Enter keys simultaneously. See screenshot: Then you will get the future closest date to today in cell B2.
To convert Python datetime to string, use the strftime() function. The strftime() method is a built-in Python method that returns the string representing date and time using date, time, or datetime object.
This function will return the datetime
in items
which is the closest to the date pivot
.
def nearest(items, pivot): return min(items, key=lambda x: abs(x - pivot))
The good part this function works on types other than datetime
too out of the box, if the type supports comparison, subtraction and abs
, e.g.: numbers and vector types.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With