Find the closest date to a given date

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.

Leave a Comment