Find the nearest hour

I have a list with these elements:

hours = ['19:30', '20:10', '20:30', '21:00', '22:00'] 

Assuming now it's 20:18, how can I get the "20: 10" item from the list? I want to use this to find the current show in the television guide.

+7
python arrays time
source share
6 answers
 >>> 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' 
+8
source share

easy but dirty way

 max(t for t in sorted(hours) if t<=now) 
+5
source share

I am not a Python programmer, but I would use the following algorithm:

  • Convert everything to β€œminutes after midnight,” for example. hours = [1170 (= 19*60+30), 1210, ...] , currenttime = 1218 (= 20*60+18) .

  • Then simply loop through thorugh hours and find the last entry that is less than currenttime .

+2
source share

You can use functions in the time module; time.strptime() allows you to parse a string in a time court, then time.mktime() converts it to seconds. Then you can simply compare all the items in seconds and find the smallest difference.

+1
source share
 import bisect # you can use the time module like katrielalex answer which a standard library # in python, but sadly for me i become an addict to dateutil :) from dateutil import parser hour_to_get = parser.parse('20:18') hours = ['19:30', '20:10', '20:30', '21:00', '22:00'] hours = map(parser.parse, hours) # Convert to datetime. hours.sort() # In case the list of hours isn't sorted. index = bisect.bisect(hours, hour_to_get) if index in (0, len(hours) - 1): print "there is no show running at the moment" else: print "running show started at %s " % hours[index-1] 

Hope this can help you :)

+1
source share

@katrielalex and Tim

 import itertools [x for x in itertools.takewhile( lambda t: now > datetime.datetime.strptime(t, "%H:%M"), hours )][-1] 
+1
source share

All Articles