find nearest time in datetime list

Tim Golden mail at timgolden.me.uk
Wed Jan 30 13:01:51 CET 2008


washakie wrote:
> Hello,
> 
> 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... 

<code>
import datetime

dates = [datetime.date (2007, 1, (1+i)*2) for i in range (10)]
one_date = datetime.date (2007, 1, 7)

print sorted (dates, key=lambda x: abs (x-one_date))[0]

</code>


TJG



More information about the Python-list mailing list