比较2个日期时间列表并找到最接近的匹配

时间:2017-06-29 10:00:01

标签: python timedelta python-datetime

我有一个日期列表,我需要根据它们的接近程度与另一个日期列表进行比较...

List1 = ['2017/03/27 23:01:45', '2017/03/28 02:00:10', ...]
List2 = ['2017/03/27 22:35:18', '2017/04/24 05:30:24', ...]

(两个列表中的日期时间对象)

我正在比较时差如下:

from datetime import timedelta

for dates1 in range(0, len(list1)):
      for dates2 in range(0, len(list2)):
           date_difference = list1[dates1] - list2[dates2]

           if timedelta(hours=0) <= date <= timedelta(hours = 12):
                   do something.... 

我遇到的问题是我有时会得到2个或更多符合日期标准的日期在12小时之内...我希望CLOSEST一个日期差异并且只是使用它...但是我不知道如何用这种设计做到这一点......

任何帮助表示感谢。

3 个答案:

答案 0 :(得分:2)

closest_dates = [min([d2 for d2 in list2 if d2 >= d1], key=lambda d: d - d1)
                 for d1 in list1]

答案 1 :(得分:0)

你可以这样做,

for d1 in List1:
    for d2 in List2:
        print(abs(d1 - d2)
        if abs(d1 - d2) < r:
            new_d1 = d1
            new_d2 = d2
            diff = abs(d1 - d2)

In [39]: new_d1
Out[37]: '2017/03/28 02:00:10'

In [39]: new_d2
Out[39]: '2017/03/27 22:35:18'

In [38]: diff
Out[38]: datetime.timedelta(0, 12292)

答案 2 :(得分:0)

您可以创建一个生成器函数来返回匹配您的条件的日期,然后创建具有最小时差的拍摄对:

from itertools import product

def interval_diff(x, y):
    for dt1, dt2 in product(x, y):
        diff = dt1 - dt2
        if timedelta(hours=0) <= diff <= timedelta(hours=12):
            yield dt1, dt2, diff

date1, date2 = min(interval_diff(list1, list2), key=lambda x: x[2])[:2]