2

这将始终打印错误。如何检查日期是否在数组中并打印正确的内容?

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"
4

2 回答 2

10

您正在将字符串与 pythondatetime.date对象进行比较;您需要使用以下.strftime()方法将日期对象转换为字符串以进行比较:

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()方法:

>>> date.today().isoformat()
'2012-08-28'
于 2012-08-28T01:01:14.973 回答
-1

您始终可以使用 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
于 2012-08-28T01:31:11.833 回答