简体   繁体   English

获取最接近给定日期的日期列表的索引

[英]Obtain the index of a list of dates that is the closest to a given date

I have the following date : 我有以下date

date=np.datetime64 (2019-12-15)

then I have a list of np.datetime64 dates: 然后我有一个np.datetime64日期列表:

['2018-01-01','2019-01-01','2019-04-12','2019-12-01']

I would like to obtain the index from the list which is closest to my date. 我想从最接近我的日期的list获取index

The desired output would be 3 which is the position of the list of dates closer to my date. 所需的输出将是3 ,这是更接近我的日期的日期列表的位置。

I am not able to provide an example given I dont know how to test my issue. 如果我不知道如何测试我的问题,则无法提供示例。

I can only think of an assert.AlmostEqual but I am not sure on how to reflect it on an example. 我只能想到一个assert.AlmostEqual但是我不确定如何在示例中体现它。

Express your list as a numpy array and just find the index of the smallest difference using np.argmin : 将您的列表表示为numpy数组,并使用np.argmin找到最小差异的索引:

import numpy as np

date = np.datetime64('2019-12-15')
array = np.array(['2018-01-01','2019-01-01','2019-04-12','2019-12-01'],
                 dtype=np.datetime64)

result = np.argmin(np.abs(array - date))

According to the datetime documentation, you can calculate timedeltas by simply subtracting the dates. 根据日期时间文档,您可以通过简单地减去日期来计算时间增量。

#Set date
date=np.datetime64 ('2019-12-15')


#Create list of strings holding date values
l = ['2018-01-01','2019-01-01','2019-04-12','2019-12-01']

#Convert strings to numpy dates 
l = [numpy.datetime64(x) for x in l]

#For each value in date list, subtract from start date. 
delta = [abs(x - date) for x in l]

#Set minimum index (see link below)
idx = np.argmin(d)


This will output 3 . 这将输出3

Min index code obtained from here 这里获得的最小索引代码

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM