How to Find the Closest Date to a Given Date

Find the closest date to a given date

This function will return the datetime in items which is the closest to the date pivot.

def nearest(items, pivot):
return min(items, key=lambda x: abs(x - pivot))

The good part this function works on types other than datetime too out of the box, if the type supports comparison, subtraction and abs, e.g.: numbers and vector types.

Find closest date from array of objects to given date

If you need to find the closest date to now, you should reduce your items.

While reducing, you should know how to access the date field and how to parse it. If the distance between the current (curr) and the target it less than the previous (prev), update the accumulator (prev) to be the current (curr).

const findClosest = (data, accessor, target = Date.now()) =>
data.reduce((prev, curr) => {
const a = Math.abs(accessor(curr).getTime() - target);
const b = Math.abs(accessor(prev).getTime() - target);
return a - b < 0 ? curr : prev;
});

const sampleData = [
{ "name": "A", "date": "31/12/2000" },
{ "name": "B", "date": "31/12/2010" },
{ "name": "C", "date": "31/12/2100" }
];

const processDateString = (dateString) => {
const [ date, month, year ] = dateString.split(/\//g).map(Number);
return new Date(year, month - 1, date);
};

const closest = findClosest(sampleData, ({ date }) => processDateString(date));

console.log(closest);

How do I find the closest date to a given date?

Following through on Henrik's suggestion to use findInterval. We can do:

library(zoo)
interval.idx <- findInterval(index(dates.zoo), index(monthly.zoo))
interval.idx <- ifelse(interval.idx == 0, NA, interval.idx)
dates.zoo$month <- index(monthly.zoo)[interval.idx]

Python Pandas how to get nearest date to a given date

IIUC, you can use idxmin on the difference between the column and the said latest_date:

latest_date = '05-2020'
print (dates.loc[(pd.to_datetime(dates['date'])
-pd.to_datetime(latest_date)).abs().idxmin(),
'date'])
'04-2020'

Find the closest date from today in a list

You can do:

min(scheduledatelist, key=lambda s: 
datetime.datetime.strptime(s, "%Y-%m-%d").date()-datetime.date.today())

For the single closest date to today.

You can use the same function to sort by distance from today:

sorted(scheduledatelist, key=lambda s: 
datetime.datetime.strptime(s, "%Y-%m-%d").date()-datetime.date.today())

And the returned list will be in increasing distance in days from today. Works if the dates are before or after today.

If you want only dates in the future, filter out the dates in the past. Since the date strings are in ISO 8601 format, you can compare lexically:

min([d for d in scheduledatelist if d>str(datetime.date.today())], key=lambda s: 
datetime.datetime.strptime(s, "%Y-%m-%d").date()-datetime.date.today())

Find closest past date in list of dates

Using min with two keys would be one way:

from datetime import datetime

now = datetime.now()
min(datelist, key=lambda x: (x>now, abs(x-now)) )

Output:

datetime.datetime(2020, 1, 31, 0, 0)

How would I go about finding the closest date to a specified date? (Java)

You can solve in linear time by computing the difference in time (e.g. Date#getTime()) and returning the minimum:

public static Date getNearestDate(List<Date> dates, Date currentDate) {
long minDiff = -1, currentTime = currentDate.getTime();
Date minDate = null;
for (Date date : dates) {
long diff = Math.abs(currentTime - date.getTime());
if ((minDiff == -1) || (diff < minDiff)) {
minDiff = diff;
minDate = date;
}
}
return minDate;
}

[Edit]

Minor performance improvements.

How To Find A Closest Date To a Given Date?

Here's one way to achieve it – assuming that the Date columns' dtype is datetime: First,

df3 = df1[df1.ID.isin(df2.ID)]

will give you

   ID       Date
0 1 2020-01-01
1 2 2020-01-03

Then

df3['Closest_date'] = df3.apply(lambda row:min(df2[df2.ID.eq(row.ID)].Date, 
key=lambda x:abs(x-row.Date)),
axis=1)
  • gets the min of df2.Date, where
  • df2[df2.ID.eq(row.ID)].Date is getting the rows that have the matching ID and
  • key=lambda x:abs(x-row.Date) is telling min to compare by distance,
  • which has to be done on rows, so axis=1

Output:

   ID       Date Closest_date
0 1 2020-01-01 2020-01-30
1 2 2020-01-03 2020-03-31


Related Topics



Leave a reply



Submit