且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

找到指定日期最近的日期

更新时间:2023-01-31 16:36:48

$($,$)$ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ c>

请注意,这也适用于数字。


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.

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

Note that this will work for numbers too.