这将始终打印 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"
您正在将字符串与 python 进行比较datetime.date
物体;您需要将日期对象转换为字符串以进行比较,使用.strftime() method http://docs.python.org/library/datetime.html#datetime.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() method http://docs.python.org/library/datetime.html#datetime.date.isoformat,它使用完全相同的输出格式:
>>> date.today().isoformat()
'2012-08-28'
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)