user3600497 user3600497 - 3 years ago 391
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


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
, the former item should be returned because it is closest to
in absolute value.

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

Note that this will work for numbers too.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download