Open In App

Python – Find the closest date from a List

Last Updated : 11 Apr, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Given a date and list of dates, the task is to write a python program to find the nearest date in the given input list of dates to the input date.

Examples:

Input : test_date_list = [datetime(2020, 4, 8), datetime(2016, 8, 18), datetime(2018, 9, 24), datetime(2019, 6, 10), datetime(2021, 8, 10)], test_date = datetime(2017, 6, 6)
Output : 2016-08-18 00:00:00
Explanation : Nearest date to 6 June 2017 is 18 August 2016 in list.

Input : test_date_list = [datetime(2020, 4, 8), datetime(2016, 8, 18), datetime(2018, 9, 24), datetime(2019, 6, 10), datetime(2021, 8, 10)], test_date = datetime(2016, 6, 6)
Output : 2016-08-18 00:00:00
Explanation : Nearest date to 6 June 2016 is 18 August 2016 in list.

Method #1 : Using min() + dictionary comprehension + abs()

In this, a difference of each date with a given date is computed as key and date as a value using abs(). The min(), is used to get the minimum key difference and its value is the result.

Python3




# Python3 code to demonstrate working of
# Nearest date in List
# Using min() + dictionary comprehension + abs()
from datetime import datetime
 
# initializing datelist
test_date_list = [datetime(2020, 4, 8), datetime(2016, 8, 18),
                  datetime(2018, 9, 24), datetime(2019, 6, 10),
                  datetime(2021, 8, 10)]
              
# printing original list
print("The original list is : " + str(test_date_list))
 
# initializing test date
test_date = datetime(2017, 6, 6)
 
# get all differences with date as values
cloz_dict = {
  abs(test_date.timestamp() - date.timestamp()) : date
  for date in test_date_list}
 
# extracting minimum key using min()
res = cloz_dict[min(cloz_dict.keys())]
 
# printing result
print("Nearest date from list : " + str(res))


Output:

The original list is : [datetime.datetime(2020, 4, 8, 0, 0), datetime.datetime(2016, 8, 18, 0, 0), datetime.datetime(2018, 9, 24, 0, 0), datetime.datetime(2019, 6, 10, 0, 0), datetime.datetime(2021, 8, 10, 0, 0)]

Nearest date from list : 2016-08-18 00:00:00

Time complexity: O(n*logn)
Auxiliary space: O(n) 

Method #2 : Using min() + abs() + lambda

Another simpler way to solve this problem is to get differences and capture the minimum one using min(). This is a flexible method and can be extended to every datatype not only datetime. 

Python3




# Python3 code to demonstrate working of
# Nearest date in List
# Using min() + abs() + lambda
from datetime import datetime
 
# initializing datelist
test_date_list = [datetime(2020, 4, 8), datetime(2016, 8, 18),
                  datetime(2018, 9, 24), datetime(2019, 6, 10),
                  datetime(2021, 8, 10)]
              
# printing original list
print("The original list is : " + str(test_date_list))
 
# initializing test date
test_date = datetime(2017, 6, 6)
 
# shorthand using lambda function for compact solution
res = min(test_date_list, key=lambda sub: abs(sub - test_date))
 
# printing result
print("Nearest date from list : " + str(res))


Output:

The original list is : [datetime.datetime(2020, 4, 8, 0, 0), datetime.datetime(2016, 8, 18, 0, 0), 

datetime.datetime(2018, 9, 24, 0, 0), datetime.datetime(2019, 6, 10, 0, 0), datetime.datetime(2021, 8, 10, 0, 0)]

Nearest date from list : 2016-08-18 00:00:00

Approach#3:Using sorted

Sort the list of dates in ascending order. Iterate through the sorted list and find the first date that is greater than or equal to the test date. Compare this date and the previous date in the list to determine which date is closer to the test date. Return the closer date as the closest date.

Algorithm

1. Sort the list of dates in ascending order.
2. For each date in the sorted list:
a. If the date is greater than or equal to test_date:
i. If the difference between date and test_date is less than the difference between previous_date and test_date, return date.
ii. Otherwise, return previous_date.
b. Set previous_date to date
3. Return the last date in the sorted list.

Python3




from datetime import datetime
 
def closest_date(date_list, test_date):
    sorted_list = sorted(date_list)
    previous_date = sorted_list[-1]
    for date in sorted_list:
        if date >= test_date:
            if abs((date - test_date).days) < abs((previous_date - test_date).days):
                return date
            else:
                return previous_date
        previous_date = date
    return sorted_list[-1]
 
# example usage
date_list = [datetime(2020, 4, 8), datetime(2016, 8, 18), datetime(2018, 9, 24), datetime(2019, 6, 10), datetime(2021, 8, 10)]
test_date = datetime(2017, 6, 6)
closest = closest_date(date_list, test_date)
print(closest)


Output

2016-08-18 00:00:00

Time complexity of the code is O(nlogn) due to the sorting operation and the linear search through the sorted list.

The space complexity is O(n) because we are creating a sorted copy of the input list.



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads