如何在 python 中验证日期字符串格式?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16870663/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I validate a date string format in python?
提问by codemickeycode
I have a python method which accepts a date input as a string.
我有一个 python 方法,它接受日期输入作为字符串。
How do I add a validation to make sure the date string being passed to the method is in the ffg. format:
如何添加验证以确保传递给方法的日期字符串在 ffg.h 中。格式:
'YYYY-MM-DD'
if it's not, method should raise some sort of error
如果不是,方法应该引发某种错误
采纳答案by jamylak
>>> 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
回答by Jacinda
The Python dateutillibrary is designed for this (and more). It will automatically convert this to a datetimeobject for you and raise a ValueErrorif it can't.
在Python的dateutil库是专门为这个(及以上)。它会自动将它转换为一个datetime对象,ValueError如果不能,它会提高一个。
As an example:
举个例子:
>>> from dateutil.parser import parse
>>> parse("2003-09-25")
datetime.datetime(2003, 9, 25, 0, 0)
This raises a ValueErrorif the date is not formatted correctly:
ValueError如果日期格式不正确,则会引发一个:
>>> parse("2003-09-251")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Users/jacinda/envs/dod-backend-dev/lib/python2.7/site-packages/dateutil/parser.py", line 720, in parse
return DEFAULTPARSER.parse(timestr, **kwargs)
File "/Users/jacinda/envs/dod-backend-dev/lib/python2.7/site-packages/dateutil/parser.py", line 317, in parse
ret = default.replace(**repl)
ValueError: day is out of range for month
dateutilis also extremely useful if you start needing to parse other formats in the future, as it can handle most known formats intelligently and allows you to modify your specification: dateutilparsing examples.
dateutil如果您以后开始需要解析其他格式,它也非常有用,因为它可以智能地处理大多数已知格式并允许您修改规范:dateutil解析示例。
It also handles timezones if you need that.
如果您需要,它还可以处理时区。
Update based on comments: parsealso accepts the keyword argument dayfirstwhich controls whether the day or month is expected to come first if a date is ambiguous. This defaults to False. E.g.
基于评论的更新:parse还接受关键字参数dayfirst,该参数控制如果日期不明确,是希望日还是月先出现。这默认为 False。例如
>>> parse('11/12/2001')
>>> datetime.datetime(2001, 11, 12, 0, 0) # Nov 12
>>> parse('11/12/2001', dayfirst=True)
>>> datetime.datetime(2001, 12, 11, 0, 0) # Dec 11
回答by Mr. B
from datetime import datetime
datetime.strptime(date_string, "%Y-%m-%d")
..this raises a ValueErrorif it receives an incompatible format.
ValueError..如果它收到不兼容的格式,则会引发 a 。
..if you're dealing with dates and times a lot (in the sense of datetime objects, as opposed to unix timestamp floats), it's a good idea to look into the pytz module, and for storage/db, store everything in UTC.
..如果您经常处理日期和时间(在日期时间对象的意义上,而不是 unix 时间戳浮动),最好查看 pytz 模块,对于存储/数据库,将所有内容存储在 UTC .
回答by Eduard Stepanov
I think the full validate function should look like this:
我认为完整的验证功能应该是这样的:
from datetime import datetime
def validate(date_text):
try:
if date_text != datetime.strptime(date_text, "%Y-%m-%d").strftime('%Y-%m-%d'):
raise ValueError
return True
except ValueError:
return False
Executing just
只执行
datetime.strptime(date_text, "%Y-%m-%d")
is not enough because strptime method doesn't check that month and day of the month are zero-padded decimal numbers. For example
是不够的,因为 strptime 方法不检查月份和月份的日期是零填充的十进制数。例如
datetime.strptime("2016-5-3", '%Y-%m-%d')
will be executed without errors.
将被执行而不会出错。
回答by TimorEranAV
This is the easiest way:
这是最简单的方法:
date = datetime.now()
date = date.strftime('%Y-%m-%d_%H-%M-%S.jpg')

