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.
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.
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.
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
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.
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
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.
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.
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.