我正在尝试使用python检查用户输入的字符串是否包含日期。
类似这样的东西。
user_input = ("Enter date")
if user_input==#type of date(yyyy-mm-dd):
print(okay)
else:
print("failed")
答案 0 :(得分:1)
dateutil库是解析日期时最好的朋友:
>>> 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
>>>
如果您想更具限制性,即只接受YYYY-MM-DD
格式的日期,然后先使用正则表达式检查可能是您的事:
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
如果您不想成为相当的限制性对象,而是接受所有等格式的日期,则:
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)
答案 1 :(得分:-1)
这就是您想要的:
>>> 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