找到最近的小时

时间:2010-11-07 16:10:37

标签: python arrays time

我有一个包含这些项目的清单:

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

假设现在是20:18,我如何从列表中获得'20:10'项目?我想用它来查找电视指南中当前正在播放的节目。

6 个答案:

答案 0 :(得分:8)

>>> 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'

答案 1 :(得分:5)

简单但又脏的方式

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

答案 2 :(得分:2)

我不是Python程序员,但我使用以下算法:

  1. 将所有内容转换为“午夜后的分钟”,例如hours = [1170 (= 19*60+30), 1210, ...]currenttime = 1218 (= 20*60+18)

  2. 然后循环搜索hours,找到最后一个小于currenttime的条目。

答案 3 :(得分:1)

您可以使用时间模块中的功能; time.strptime()允许您将字符串解析为时间元组,然后time.mktime()将其转换为秒。然后,您可以在几秒钟内简单地比较所有项目,并找出最小的差异。

答案 4 :(得分: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] 

希望这可以帮助你:)

答案 5 :(得分:1)

@katrielalex&amp;添

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