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]
Find closest past date in list of dates
Using min
with two key
s 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.
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())
Pandas: Find closest date - without set_index - multiple conditions
Take a subset of relevant category, subtract the target date, and get idxmin
tmp = df.loc[df.category.eq(3)]
(tmp.date - pd.to_datetime("2000-01-02")).abs().idxmin()
# 5
Related Topics
Running Interactive Commands in Paramiko
Cannot Pass an Argument to Python with "#!/Usr/Bin/Env Python"
How to Run Python Script Without Typing 'Python ...'
Pandas Out of Bounds Nanosecond Timestamp After Offset Rollforward Plus Adding a Month Offset
How to Run an Ipython Magic from a Script (Or Timing a Python Script)
Update Tkinter Label from Variable
Use Python's String.Replace VS Re.Sub
Python Random Sample with a Generator/Iterable/Iterator
Return String with First Match for a Regex, Handling Case Where There Is No Match
Pipelinedrdd' Object Has No Attribute 'Todf' in Pyspark
How to Overwrite/Print Over the Current Line in Windows Command Line
How to Get Python's Elementtree to Pretty Print to an Xml File
Store Mouse Click Event Coordinates with Matplotlib
How to Open a Website in My Web Browser Using Python
Differencebetween .Quit and .Quit in Pygame
How to Break a Long Line to Multiple Lines in Python
How to Add a New Column to a Spark Dataframe (Using Pyspark)