0

I'm new to python, and have little experience using try & except statements. My code needs to check the date format entered by user. I'm currently using the code from this thread:

How do I validate a date string format in python?

but it's not working properly: i.e. the following do not raise an exception, where date_text = "20189901", as does date_text = "20181301"

import datetime
date_text = "20189901"
try:
    datetime.datetime.strptime(date_text, '%Y%m%d')
except ValueError:
    raise ValueError("Incorrect data format, should be YYYYMMDD")

Is there a way to check date format using a simple if statement?

Mike
  • 133
  • 1
  • 1
  • 8
  • It is possible. But why would you use an `if` statement instead of `try` / `except`? – jpp Feb 18 '18 at 22:42
  • 1
    What do you mean? It raises the exception for me. – Anton vBR Feb 18 '18 at 22:45
  • not sure if this is what you want but to avoid your problem you could just replace, `except ValueError: raise ValueError("Incorrect data format, should be YYYYMMDD")` with `except: print("Incorrect data format, should be YYYYMMDD")` – Nazim Kerimbekov Feb 18 '18 at 23:23
  • date_text = "20189901" and "20181301" are both invalid dates. The code above doesn't recognise this, and treats them as valid.. except ValueError is not 'triggering'.I would prefer an if statement, but try / except is fine.. I just need it to work properly – Mike Feb 19 '18 at 01:45

0 Answers0