本文介绍了如何在 python 中验证日期字符串格式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个 python 方法,它接受日期输入作为字符串.
I have a python method which accepts a date input as a string.
如何添加验证以确保传递给方法的日期字符串在 ffg.h 中.格式:
How do I add a validation to make sure the date string being passed to the method is in the ffg. format:
'YYYY-MM-DD'
如果不是,方法应该引发某种错误
if it's not, method should raise some sort of error
推荐答案
>>> 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
这篇关于如何在 python 中验证日期字符串格式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!