2012-08-28 31 views
1

這將始終打印錯誤。我怎樣才能檢查日期是否在陣列中,並打印適當的東西?如何檢查日期是否在日期字符串列表中?

dates = [ "2012-09-03", 
"2012-10-08", 
"2012-10-09", 
"2012-11-12", 
# .. more values snipped for brevity 
"2013-04-19", 
"2013-05-27", ] 

if date.today() in dates: 
    print "true" 
elif date.today() not in dates: 
    print "false" 

回答

8

您正在比較python datetime.date對象的字符串;您需要將日期對象轉換爲比較字符串,使用.strftime() method

today = date.today().strftime('%Y-%m-%d') 
print today in dates # Will print "True" or "False" 

爲了進一步說明這一點:或者

>>> from datetime import date 
>>> date.today() 
datetime.date(2012, 8, 28) 
>>> date.today() == '2012-08-28' 
False 
>>> date.today().strftime('%Y-%m-%d') == '2012-08-28' 
True 

,您可以使用.isoformat() method,它使用完全相同的輸出格式:

>>> date.today().isoformat() 
'2012-08-28' 
0

您可以隨時使用index()函數和try/except函數來測試日期是否在您的lis中t像這樣:

list = [1,2,3,4,5,6,7,8,9] 
try: 
    location = list.index(5) 
    print("5 was found in the list.") # if program manages to get 
            # here you know 5 is in 
            # the list. 
except: 
    print("5 was no found in the list.") # if it doesn't find 5 this 
             # line is displayed 
+2

但是'dates.index(date.today())'不會更有用.. – 2012-08-28 01:44:50

相關問題