2

I have a list of datetime objects and want to find the closest 5 (or 6 or 7 etc.) dates that correspond with my specified date.

For instance:

datelist
>>>> [datetime.date(2017, 3, 4), datetime.date(2017, 3, 6), datetime.date(2017, 3, 12), datetime.date(2017, 3, 27), datetime.date(2017, 3, 27), datetime.date(2017, 3, 29), datetime.date(2017, 3, 29), datetime.date(2017, 4, 2), datetime.date(2017, 4, 4)]

If I type:

my_date = datetime.date(2017, 4, 2)
nearest_list = find_nearest(datelist, my_date)  # Functionality I want!

print nearest_list
>>>> [datetime.date(2017, 3, 27), datetime.date(2017, 3, 29), datetime.date(2017, 3, 29), datetime.date(2017, 4, 2), datetime.date(2017, 4, 4)]

I should receive a list of the nearest 5 dates.

I know that I could find the nearest date and take the two list elements either side of this (as datelist is sorted) but this is difficult when the nearest date may be the first or last element (i.e. no items before or after, respectively).

1 Answer 1

6

You can use sorted with a custom function:

res = sorted(datelist, key=lambda x: abs(x-my_date))[:5]

[datetime.date(2017, 4, 2),
 datetime.date(2017, 4, 4),
 datetime.date(2017, 3, 29),
 datetime.date(2017, 3, 29),
 datetime.date(2017, 3, 27)]
Sign up to request clarification or add additional context in comments.

1 Comment

Well that's pretty neat

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.