Python - Find the closest date from a List
Last Updated :
11 Apr, 2023
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.
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)
Output2016-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.
Similar Reads
Python | Find the closest Key in dictionary The search of keys in dictionary in python has been discussed many times. But sometimes, we may have a problem in which we require to fetch the key which is the nearest one of the given keys. Let's discuss certain ways in which this task can be performed. Method #1 : Using list comprehension + keys(
2 min read
Python - Find consecutive dates in a list of dates Given a list of dates, the task is to write a Python program to check if all the dates are consecutive in the list. Input : [datetime(2019, 12, 30), datetime(2019, 12, 31), datetime(2020, 1, 1), datetime(2020, 1, 2), datetime(2020, 1, 3), datetime(2020, 1, 4)] Output : True Explanation : All dates a
4 min read
Python | Find closest number to k in given list Given a list of numbers and a variable K, where K is also a number, write a Python program to find the number in a list which is closest to the given number K. Examples: Input : lst = [3.64, 5.2, 9.42, 9.35, 8.5, 8], K = 9.1 Output : 9.35 Input : lst = [9, 11, 5, 3, 25, 18], K = 6 Output : 5 Method
5 min read
Creating a list of range of dates in Python Given a date, the task is to write a Python program to create a list of a range of dates with the next k dates starting from the current date. For example, if the given date is 4th January 1997 and k is 5, the output should be a list containing 4th January 1997, 5th January 1997, 6th January 1997, 7
3 min read
Python - Closest Sum Pair in List Sometimes, we desire to get the elements that sum to a particular element. But in cases we are not able to find that, our aim changes to be one to find the closest one. This can have application in many domains. Lets discuss certain ways in which this task can be performed. Method #1 : Using diction
4 min read
Python Program to Find closest number in array Given an array of sorted integers. We need to find the closest value to the given number. Array may contain duplicate values and negative numbers. Examples: Input : arr[] = {1, 2, 4, 5, 6, 6, 8, 9} Target number = 11 Output : 9 9 is closest to 11 in given array Input :arr[] = {2, 5, 6, 7, 8, 8, 9};
4 min read