I am trying to check if the string entered by the user contains date using python.
something like this.
user_input = ("Enter date")
if user_input==#type of date(yyyy-mm-dd):
print(okay)
else:
print("failed")
I am trying to check if the string entered by the user contains date using python.
something like this.
user_input = ("Enter date")
if user_input==#type of date(yyyy-mm-dd):
print(okay)
else:
print("failed")
The dateutil library is your best friend when it comes to parsing dates:
>>> from dateutil.parser import *
>>> parse('2003-12-23')
datetime.datetime(2003, 12, 23, 0, 0)
>>> parse('2003-12-32')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "c:\srv\venv\dev\lib\site-packages\dateutil\parser\_parser.py", line 1356, in parse
return DEFAULTPARSER.parse(timestr, **kwargs)
File "c:\srv\venv\dev\lib\site-packages\dateutil\parser\_parser.py", line 653, in parse
ret = self._build_naive(res, default)
File "c:\srv\venv\dev\lib\site-packages\dateutil\parser\_parser.py", line 1227, in _build_naive
naive = default.replace(**repl)
ValueError: day is out of range for month
>>>
If you want to be more restrictive, ie. only accept dates with the YYYY-MM-DD
format, then checking with a regex first might be your thing:
def is_date(ds):
if re.match(r'\d{4}-\d{2}-\d{2}', ds):
return bool(parse(ds))
return False
>>> is_date('2003-12-23')
True
>>> is_date('2003-12-32')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 3, in is_date
File "c:\srv\venv\dev\lib\site-packages\dateutil\parser\_parser.py", line 1356, in parse
return DEFAULTPARSER.parse(timestr, **kwargs)
File "c:\srv\venv\dev\lib\site-packages\dateutil\parser\_parser.py", line 653, in parse
ret = self._build_naive(res, default)
File "c:\srv\venv\dev\lib\site-packages\dateutil\parser\_parser.py", line 1227, in _build_naive
naive = default.replace(**repl)
ValueError: day is out of range for month
If you don't want to be quite as restrictive, but accept all iso-formatted dates, then:
from dateutil.parser import isoparse
>>> isoparse('2003-12-23')
datetime.datetime(2003, 12, 23, 0, 0)
>>> isoparse('20031223')
datetime.datetime(2003, 12, 23, 0, 0)
This is what you want:
>>> import datetime
>>> def validate(date_text):
try:
datetime.datetime.strptime(date_text, '%Y-%m-%d')
except ValueError:
raise ValueError("Incorrect data format, should be YYYY-MM-DD")
>>> validate('2003-12-23')
>>> validate('2003-12-32')
Traceback (most recent call last):
File "<pyshell#20>", line 1, in <module>
validate('2003-12-32')
File "<pyshell#18>", line 5, in validate
raise ValueError("Incorrect data format, should be YYYY-MM-DD")
ValueError: Incorrect data format, should be YYYY-MM-DD