Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find the closest date to a given date

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.

like image 675
user3600497 Avatar asked Aug 26 '15 22:08

user3600497


People also ask

How do I find the closest date in Excel?

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.

How do I convert a date to a string in Python?

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.


1 Answers

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.

like image 63
Tamas Hegedus Avatar answered Oct 04 '22 15:10

Tamas Hegedus