2017-07-17 49 views
-2

我在Python上使用Json搞了一點,我想讀tvmaze.com提供的API。雖然我可以得到項目很好,但名單很長,我想限制它從我的本地時鐘+1小時。例如,如果我的計算機時鐘是15:00,以便在16:30到15:30之間向我顯示這些項目,則會在16:30之前向我顯示這些項目。在PHP中,我會添加3600秒到當前時間,但在Python中,整個時間三角洲似乎令人困惑。來自Feed的Python打印項目匹配當前時間1小時後

這是我目前使用的

import urllib2 
import simplejson 

response = urllib2.urlopen("http://api.tvmaze.com/schedule?country=US&date=2017-07-17") 
data = simplejson.load(response) 
myList=["abc","amc","animal planet","bravo","cartoon network","cbs","comedy central","the cw","discovery channel","fox","freeform","hbo","history","mtv","nbc","nickelodeon","tbs","tnt","usa network","wwe network"] 
for post in data: 
    if post["show"]["network"]["name"].lower() in myList: 
     airtime = post["airtime"] 
     network = post["show"]["network"]["name"] 
     name = post["show"]["name"] 
     season = post["season"] 
     ep = post["number"] 
     time = post["show"]["schedule"]["time"] 
     date = post["airdate"] 
     #summary = ["show"]["summary"] 
     print airtime,"",name,"- Season",season,"EP",ep,"("+network+")" 

樣本輸出的Python代碼:

21:00 Preacher - Season 2 EP 5 (AMC) 
21:00 Will - Season 1 EP 3 (TNT) 
21:00 American Pickers - Season 17 EP 10 (History) 
21:00 Stitchers - Season 3 EP 6 (FreeForm) 
21:00 Superhuman - Season 1 EP 6 (FOX) 
21:00 Whose Line Is It Anyway? - Season 13 EP 6 (The CW) 
21:00 Teen Mom 2 - Season 8 EP 1 (MTV) 
21:00 Street Outlaws: New Orleans - Season 2 EP 4 (Discovery Channel) 
21:00 The Real Housewives of Orange County - Season 12 EP 2 (Bravo) 
21:00 Teen Mom - Season 7 EP 30 (MTV) 
21:00 Alaska: The Last Frontier: The Frozen Edge - Season 4 EP 13 (Animal Planet) 

回答

1

您可以輕鬆地獲取您的當前時間和使用datetime模塊添加任何偏移到它,比如:

import datetime 

current_datetime = datetime.datetime.now() # local date and time 
current_time = datetime.datetime.time(current_datetime) # time only 
plus_hour = datetime.datetime.time(current_datetime + datetime.timedelta(hours=1)) # +1h 

現在,如果你想對「過濾器」,你可以隨時把從數據你打電話到一個時間對象,然後將API相比,但在你的情況下一個確切的時間你需要的是比較小時,進入到你的plus_hour時間的分鐘,例如:

split_time = post["airtime"].split(":") # split the time field 
time_hour = time_minute = 0 # initialize as both as `0` 
if len(split_time) >= 2: 
    time_hour = int(split_time[0]) 
    time_minute = int(split_time[1]) 
elif len(split_time) > 0: 
    time_hour = int(split_time[0]) 
if int(time_hour) != plus_hour.hour and int(time_minute) != plus_hour.minute: 
    continue # no match, move to the next item... 
+0

我顯然做錯了,因爲我得到一個錯誤ValueError:需要更多超過1個值才能解包。 – Slightz

+0

比它意味着某些'post [「通話時間」]不包含有效時間,請檢查更新。 – zwer

+0

我將如何實現與我的代碼?在for循環中添加if和elif? – Slightz

0

的時間增量可能看起來混亂,但它是這個職位的最佳工具。

下面是我在Python中處理timedeltas時通常採用的方法。希望這會對你更具可讀性。

>>> from datetime import datetime, timedelta 
>>> now = datetime.utcnow() 
>>> def hour_past(dt): 
...  return dt + timedelta(hours=1) 
... 
>>> hour_from_now = hour_past(now) 
>>> hour_from_now > now 
True 

不可否認,它與datetime秒且不time S,不過這只是我個人比較喜歡的,因爲utcnow()的可靠性。

相關問題