这将始终打印为false。如何检查日期是否在数组中并打印出正确的内容?
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"
答案 0 :(得分:9)
您正在将字符串与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'
答案 1 :(得分:0)
您总是可以使用index()函数和try / except函数来测试日期是否在列表中,如下所示:
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