arsenal88
arsenal88

Reputation: 1160

Finding the closest datetimes in 2 lists

I have 2 lists (examples below, but real one has 100+ in each list):

ListA = [29/11/2017 03:44:42, 23/11/2017 07:36:35, etc....]
ListB = [12/09/2017 02:00:34, 12/05/2017 14:00:25, etc....]

I'm trying to go through every element in ListA and find out which element in ListB is closest to that date. I'm struggling to do so though.

I first made sure both lists elements are datetime objects.

But after this, I keep coming up stuck... I'm probably thinking about this wrong.

for i in ListA:
    closestTimestamp = min(key, key=lambda datetime: abs(timestamp - [j for j in ListB]))

It's saying key is not defined. I'm very new to Python to apologies if this is a silly question.

Upvotes: 1

Views: 462

Answers (1)

Eugene Yarmash
Eugene Yarmash

Reputation: 149736

You should pass an iterable (e.g. ListB) and a key function to min(). Try this:

for a in ListA:
    closestTimestamp = min(listB, key=lambda b: abs(a-b))

BTW, the time complexity of this solution is O(nm), which may be slow for bigger lists. In that case consider using binary search for O(nlogm) complexity.

Upvotes: 2

Related Questions