Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the closest datetime from a list

in Python, if I have a datetime and a list of datetimes, e.g.:

import datetime as dt
date = dt.datetime(1970, 1,1)

dates = [dt.datetime(1970, 1, 2), dt.datetime(1970, 1,3)]

How I can get the datetime in the list that's closest to date?

like image 927
JuanPablo Avatar asked Apr 17 '15 13:04

JuanPablo


2 Answers

You can use min with a custom key parameter:

>>> import datetime as dt
>>> date = dt.datetime(1970, 1, 1)
>>> dates = [dt.datetime(1970, 1, 2), dt.datetime(1970, 1, 3)]
>>> min(dates, key=lambda d: abs(d - date))
datetime.datetime(1970, 1, 2, 0, 0)

Subtracting two datetime objects gives a timedelta object:

>>> map(lambda d: abs(d - date), dates)
[datetime.timedelta(1), datetime.timedelta(2)]

which behaves as you'd expect in comparisons.

like image 116
jonrsharpe Avatar answered Oct 08 '22 07:10

jonrsharpe


If they are in order you could also use bisect:

import datetime as dt
date = dt.datetime(1970, 1, 1,12)

dates = [dt.datetime(1970, 1, 2), dt.datetime(1970, 1,3)]

from bisect import bisect

ind = bisect(dates, date, hi=len(dates)-1)

print(min(dates[ind], dates[ind-1],key=lambda x: abs(x - date)))

Finding the upper bound is O(log n) and then we just compare the upper with the lower element which is dates[ind-1], so for a sorted list it is O(log n) vs O(n).

like image 38
Padraic Cunningham Avatar answered Oct 08 '22 06:10

Padraic Cunningham