jeudi 6 mai 2021

why is elif not working in my example in Python?

I've read several other questions about this subject and my identation seems correct, I really dont understand why the code below is not working!

import datetime
def validate(date_text):
  if datetime.datetime.strptime(date_text, '%Y-%m-%d'):
    print('format is YMD')
  elif datetime.datetime.strptime(date_text, '%Y-%d-%m'):
    print('format is YDM')
  elif datetime.datetime.strptime(date_text, '%d-%m-%Y'):
    print('format is DMY')
  elif datetime.datetime.strptime(date_text, '%m-%d-%Y'):
    print('format is MDY')
  else:
    print('other')

validate('2003-12-23') 

This works...

validate('2003-23-12') 

This does not work! i get the following error:

---------------------------------------------------------------------------

ValueError                                Traceback (most recent call last)

<ipython-input-45-d6fe5c34e65c> in <module>()
----> 1 validate('2003-23-12')

2 frames

/usr/lib/python3.7/_strptime.py in _strptime(data_string, format)
    357     if not found:
    358         raise ValueError("time data %r does not match format %r" %
--> 359                          (data_string, format))
    360     if len(data_string) != found.end():
    361         raise ValueError("unconverted data remains: %s" %

ValueError: time data '2003-23-12' does not match format '%Y-%m-%d'

Thank you in advane for your help, I really don't understand why it does not work! my identations seem correct.

Aucun commentaire:

Enregistrer un commentaire