find nearest time in datetime list
Tim Chase
python.list at tim.thechases.com
Wed Jan 30 07:06:31 EST 2008
> I have a list of datetime objects: DTlist, I have another single datetime
> object: dt, ... I need to find the nearest DTlist[i] to the dt .... is
> there a simple way to do this? There isn't necessarily an exact match...
import datetime
dates = [datetime.datetime(2007,m, 1) for m in range(1,13)]
test_date = datetime.datetime(2007,4,15)
closest = sorted(dates, key=lambda d: abs(test_date - d))[0]
print closest
-tkc
More information about the Python-list
mailing list