user3600497 user3600497 - 1 month ago 17
Python Question

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.

Answer
def nearest(items, pivot):
    return min(items, key=lambda x: abs(x - pivot))

Note that this will work for numbers too.

Comments