in Python, if I have a datetime
and a list of datetime
s, 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
?
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.
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)
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With