Find the closest hour
I have a list with these items:
hours = ['19:30', '20:10', '20:30', '21:00', '22:00']
Assuming that now it's 20:18, how can I get the '20:10' item from list? I want to use this to find the current r开发者_JAVA技巧unning show in a TV Guide.
>>> 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:
Convert everything to "minutes after midnight", e.g.
hours = [1170 (= 19*60+30), 1210, ...]
,currenttime = 1218 (= 20*60+18)
.Then just loop thorugh
hours
and find the last entry which is smaller thancurrenttime
.
You can use functions in the time module; time.strptime()
allows you to parse a string into a time-tuple, then time.mktime()
converts this to seconds. You can then simply compare all items in seconds, and find the smallest difference.
@katrielalex & Tim
import itertools
[x for x in itertools.takewhile( lambda t: now > datetime.datetime.strptime(t, "%H:%M"), hours )][-1]
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 :)
精彩评论