如何检查日期是否在日期字符串列表中? [英] How to check if date is in a list of date strings?

查看:76
本文介绍了如何检查日期是否在日期字符串列表中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这将始终打印为false.如何检查日期是否在数组中并打印正确的东西?

This will always print false. How can I check if the date is in the array and print the proper thing?

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

You are comparing strings with python datetime.date objects; you need to convert the date object to a string for the comparison, using the .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()方法 ,它使用完全相同的输出格式:

Alternatively, you can use the .isoformat() method, which uses the exact same output format:

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

这篇关于如何检查日期是否在日期字符串列表中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆