Find the closest hour Find the closest hour arrays arrays

Find the closest hour


>>> import datetime>>> hours = ['19:30', '20:10', '20:30', '21:00', '22:00']>>> now = datetime.datetime.strptime("20:18", "%H:%M")>>> min(hours, key=lambda t: abs(now - datetime.datetime.strptime(t, "%H:%M")))'20:10'


easy but dirty way

max(t for t in sorted(hours) if t<=now)


I'm not a Python programmer, but I'd use the following algorithm:

  1. Convert everything to "minutes after midnight", e.g. hours = [1170 (= 19*60+30), 1210, ...], currenttime = 1218 (= 20*60+18).

  2. Then just loop thorugh hours and find the last entry which is smaller than currenttime.