最接近的过去日期

最接近的过去日期

本文介绍了在日期列表中查找最接近的过去日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在日期列表中找到与当前日期最接近的过去日期.我已经找到了几个在列表中搜索最接近日期的示例,但是所有这些示例都允许选择返回更远的日期.

I'm trying to find the closest past date in a list of dates to the current date. I've found several examples of searching for the closest date in a list but all these allow for the option of a further date to be returned.

日期时间列表具有以下形式:

The list of datetimes has the following form:

datelist =
[datetime.datetime(2019, 12, 31, 0, 0),
 datetime.datetime(2020, 1, 10, 0, 0),
 datetime.datetime(2020, 1, 20, 0, 0),
 datetime.datetime(2020, 1, 31, 0, 0),
 datetime.datetime(2020, 2, 10, 0, 0),
 datetime.datetime(2020, 2, 20, 0, 0)]

到目前为止,我一直在实现以下功能以查找最接近的日期;

Up until now I have been implementing the following function to find the closest date;

def nearest_ind(items, pivot):
    '''
    Find the nearest value to the given value (the pivot) in a list.
    '''
    time_diff = np.abs([date - pivot for date in items])
    return time_diff.argmin(0)

但是这会将最接近的日期返回到当前日期,是返回将来最接近的日期的一半时间.我也一直在考虑实现numpy searchsorted函数,但这似乎总是返回最接近的将来日期,而不管我是通过以下方式为side参数选择"right"还是"left":

But this returns the closest date to the current date, half of the time this returns the closest date in the future. I've also been looking at implementing numpy searchsorted function, but this seems to always return the closest future date, regardless of whether I select "right" or "left" for the side parameter, in the following ways:

np.searchsorted(datelist, datetime.datetime.now(), side='right')
np.searchsorted(datelist, datetime.datetime.now(), side='left')

numpy searchsorted函数在任何一个实例中都返回(如果我今天要在2020年2月7日运行它)4(对应于datetime.datetime(2020,2,10,0,0)).有谁知道可以确保始终返回过去最接近的日期的方法?

The numpy searchsorted function returns (if I was to run this today, 7th February 2020) 4 (corresponding to datetime.datetime(2020, 2, 10, 0, 0)) in either instance. Does anyone know of a way to ensure the closest date in the past is always returned?

推荐答案

使用 min 和两个 key 是一种方法:

Using min with two keys would be one way:

from datetime import datetime

now = datetime.now()
min(datelist, key=lambda x: (x>now, abs(x-now)) )

输出:

datetime.datetime(2020, 1, 31, 0, 0)

这篇关于在日期列表中查找最接近的过去日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-11 02:10