Mike Savi
Mike Savi

Reputation: 673

How to check if date is in a list of date strings?

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"

Upvotes: 3

Views: 19116

Answers (2)

RandomPhobia
RandomPhobia

Reputation: 4822

You could always use the index() function and the try/except function to test if a date is in your list like so:

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

Upvotes: 0

Martijn Pieters
Martijn Pieters

Reputation: 1125398

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"

To illustrate this further:

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

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

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

Upvotes: 11

Related Questions