-1

I have a below list,

   e= [datetime.date(2011, 3, 12),
     datetime.date(2014, 3, 12),
     datetime.date(2021, 12, 12)]

And want to write a program that would check if a given date say in a function when passed, is able to check whether the date is present inside this list or not.

Here is a sample code I am trying:

def defd(a,b,c):
  if datetime.date(a,b,c)==e:
    print('Date exists')
  else:
      print('Date doesnt exists')

defd(2014,3,12)

The o/p is showing date doesnt exists, can you let me know where am i going wrong?

John
  • 279
  • 1
  • 3
  • 16
  • have you tried parsing the date instead of just passing a string – whitespace Dec 07 '21 at 03:09
  • I have edited my question, you can see now. – John Dec 07 '21 at 04:10
  • "if datetime.date(a,b,c)==e:" Well, yes, of course the `datetime.date` that you create here is not *equal to* a list, in the same way that you are not equal to the population census for your country. If the question is *actually* "how do I check whether something is in a list?", then that has nothing to do with the `datetime` class, and is also easy to answer with an internet search or by following any tutorial. – Karl Knechtel Dec 07 '21 at 04:13
  • @KarlKnechtel, the datetime list is actually coming from a class method that I created, so the list e in itself a object of the class, which I have appended to a list. Hence the reason, I am going for this approach. – John Dec 07 '21 at 04:19
  • 2
    it doesn't matter where the list comes from. If your question is "how do I check whether the list contains this datetime?", then you do that the same way you check whether anything else is in a list - by using `in`. Otherwise, you need to explain what the *actual question* is. It seems to me, based on your code, like you don't have an actual question - you just have a typo. – Karl Knechtel Dec 07 '21 at 04:20

1 Answers1

1

replace string input with datetime object

def defd(a):
    k = [datetime.datetime(2011, 11, 12),
    datetime.datetime(2014, 11, 12),
    datetime.datetime(2021, 12, 12)]
    if a in k: #k is the above list
        print('Date exists')
    else:
        print('Date doesnt exist')

defd(datetime.datetime.strptime('2011-3-12',"%Y-%m-%d")) 
whitespace
  • 789
  • 6
  • 13
  • its giving me that the date doesn't exists even for dates mentioned inside the list. – John Dec 07 '21 at 03:46