问题描述
我有一个 datetime 对象数组,我想找出数组中哪个元素最接近给定日期(例如 datetime.datetime(2014,12,16)
)
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?
例如,如果数组包含元素 datetime.datetime(2014,12,10)
和 datetime.datetime(2014,12,28)
,则前一项应该返回,因为它的绝对值最接近 datetime.datetime(2014,12,16)
.
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.
推荐答案
该函数将返回items
中最接近日期pivot的
datetime
.
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))
如果该类型支持比较、减法和
abs
,则此函数适用于除 datetime
以外的其他类型,例如:数字和向量类型.
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.
这篇关于查找最接近给定日期的日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!