Skip to content Skip to sidebar Skip to footer

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 va

Solution 1:

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'

Solution 2:

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

Post a Comment for "How To Check If Date Is In A List Of Date Strings?"