Get the Nearest Date to Specific from the List of Dates

Get the nearest date to specific from the list of dates?

  temp.stream()
.map(x -> new SimpleEntry<>(x, ChronoUnit.DAYS.between(x.getAsOfDate(), x.getValidFrom())))
.min(Comparator.comparingLong(Entry::getValue))
.map(Entry::getKey)
.orElse(...);

Or simpler:

test.stream()
.min(Comparator.comparingLong(x -> ChronoUnit.DAYS.between(x.asOfDate , x.validFrom)));

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

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())

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 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);

Given a list of dates, how do I get the nearest date in the past to today and the nearest date in the future to today in VB.NET

Seems like this is what you are looking for. you simply need to be able to pass something in to the function so it knows what you want. I chose an enum for explicitness. I also updated it to pass back a nullable date. This should correct your time issues, but you'll need to account for null returned values.

Public Enum DateCompare
LessThanEqualTo
GreaterThanEqualTo
End Enum

Public Function GetNearestDate(ByVal source As IEnumerable(Of DateTime), _
ByVal target As DateTime, _
ByVal dt As DateCompare) As Nullable(Of DateTime)
Dim result As Nullable(Of DateTime) = Nothing
Dim lowestDifference As TimeSpan = TimeSpan.MaxValue
Dim difference As TimeSpan

For Each _date As DateTime In source
If dt = DateCompare.LessThanEqualTo And _date > target Then
Continue For
ElseIf dt = DateCompare.GreaterThanEqualTo And _date < target Then
Continue For
End If

If target > _date Then
difference = target - _date
Else
difference = _date - target
End If

If difference < lowestDifference Then
lowestDifference = difference
result = _date
End If
Next

Return result
End Function

Best way to find date nearest to target in a list of dates?

Sietse de Kaper solution assumes a reverse sorted list, definitely not the most natural thing to have around

The natural sort order in java is following the ascending natural ordering. (see Collection.sort http://java.sun.com/j2se/1.5.0/docs/api/java/util/Collections.html#sort(java.util.List) documentation)

From your example,


target date = 2008-10-03
list = 2008-10-01 2008-10-02 2008-10-04

If another developper uses your method with a naive approach he would get 2008-10-01 which is not what was expected

  • Don't make assumptions as to the ordering of the list.
  • If you have to for performance reasons try to follow the most natural convention (sorted ascending)
  • If you really have to follow another convention you really should document the hell out of it.

    private Date getDateNearest(List<Date> dates, Date targetDate){
    Date returnDate = targetDate
    for (Date date : dates) {
    // if the current iteration'sdate is "before" the target date
    if (date.compareTo(targetDate) <= 0) {
    // if the current iteration's date is "after" the current return date
    if (date.compareTo(returnDate) > 0){
    returnDate=date;
    }
    }
    }
    return returnDate;
    }

    edit - I also like the Treeset answer but I think it might be slightly slower as it is equivalent to sorting the data then looking it up => nlog(n) for sorting and then the documentation implies it is log(n) for access so that would be nlog(n)+log(n) vs n



    Related Topics



  • Leave a reply



    Submit