in Python, if I have a datetime
and a list of datetime
s, eg:
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)
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.