我有一个返回这些日期的日期列表(date_list)。我现在需要找出哪个日期最接近另一个日期(base_date)。
我正在使用Python和Django来获取此数据
date_list = [datetime.date(2017, 6, 18), datetime.date(2018, 2, 4), datetime.date(2018, 2, 11), datetime.date(2018, 4, 23), datetime.date(2018, 6, 17)]
base_date = [datetime.date(2016, 4, 7)]
答案 0 :(得分:0)
import datetime
date_list = [datetime.date(2018, 2, 4),
datetime.date(2018, 2, 11),
datetime.date(2018, 4, 23),
datetime.date(2017, 6, 18),
datetime.date(2018, 6, 17)]
base_date = datetime.date(2016, 4, 7)
min_delta = min([abs(base_date - one) for one in date_list])
closest_index = delta_list.index(min_delta)
date_list [nearest_index]是最接近的
答案 1 :(得分:0)
下面的代码应该能够为您提供Python 3的预期结果。
import datetime
date_list = [datetime.date(2017, 6, 18), datetime.date(2018, 2, 4), datetime.date(2018, 2, 11), datetime.date(2018, 4, 23), datetime.date(2018, 6, 17)]
base_date = [datetime.date(2016, 4, 7)]
closest_date = ''
lowest_time_delta = 99999999
for my_date in date_list:
current_time_delta = abs((my_date - base_date[0]).total_seconds())
if current_time_delta < lowest_time_delta:
closest_date = my_date
lowest_time_delta = current_time_delta
print (closest_date)