2010-11-07 128 views
7

我與這些項目的列表:尋找最近的小時

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

假設現在是20:18,我怎麼能得到'20:從列表10' 項目?我想用它來查找電視指南中當前正在播放的節目。

+3

那你試試?爲什麼它沒有工作? – carlosdc 2010-11-07 16:15:43

+1

到目前爲止您嘗試過哪些方法無效? – 2010-11-07 16:16:28

+2

如果現在是20:25,你想要哪個結果? 20:30是最接近的,但它是未來的,所以它不能成爲當前正在運行的節目... – 2010-11-07 17:01:20

回答

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

+1爲OP做了什麼要求(找到最近的小時),但他也寫道,他想要找到「當前跑節目」 - 所以對於「20:22」你得到了「20:30」,這明顯不是當前正在運行的演出。 – 2010-11-07 16:59:11

1

您可以使用時間模塊中的函數; time.strptime()允許您將字符串解析爲時間元組,然後time.mktime()將其轉換爲秒。然後您可以在幾秒鐘內簡單比較所有項目,並找出最小的差異。

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] 

希望這可以幫助你:)

+2

這假定具有一位數小時或分鐘的時間用相應值的前導零表示。 – 2010-11-07 16:17:45

+0

他可以在調用bisect.bisect – mouad 2010-11-07 16:19:03

+0

之前將它們從頭開始轉換,如果對列表進行排序,則bisect可以工作。考慮'小時= ['19:30','20:10','20:30','23:00','21:00','22:00']' – khachik 2010-11-07 16:20:40

2

我不是一個Python程序員,但我會用下面的算法:

  1. 轉換一切「午夜分鐘後」 ,例如hours = [1170 (= 19*60+30), 1210, ...]currenttime = 1218 (= 20*60+18)

  2. 然後只是循環遍歷hours,並找到最後一個小於currenttime的條目。

+0

+1:這實際上可以解決「當前正在運行的節目」的問題。也許可能需要先排序時間。 – 2010-11-07 17:24:29

1

@katrielalex &添

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

容易的,但骯髒的方式

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