Normalizing string to date in cerbrus

廉价感情. 提交于 2020-01-04 06:43:41

问题


i'm trying to normalize string as date so that in validation it can validate date data type.

from cerberus import Validator
from datetime import datetime

v = Validator()
v.schema = {'start_date': {'type': 'date','coerce':datetime.date}}
v.validate({'start_date': '2017-10-01'})
>>> False

but it still returns false. I have tried to use the integer and it works not sure why date conversion is not working.

v = Validator()
v.schema = {'amount': {'type': 'integer','coerce': int}}
v.validate({'amount': '2'})
>>> True

Any help would be appreciated.


回答1:


I am afraid that datetime.date alone won't convert a string to a date value. If you try that in the REPL this is what you get:

>>> datetime.date('2017-10-01')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: descriptor 'date' requires a 'datetime.datetime' object but received a 'str'

Try something like this instead:

from cerberus import Validator
from datetime import datetime

v = Validator()
to_date = lambda s: datetime.strptime(s, '%Y-%m-%d')
v.schema = {'start_date': {'type': 'datetime','coerce': to_date}}
v.validate({'start_date': '2017-10-01'})
>>> True



回答2:


Maybe this way is better to use:

def to_date(s):
    return datetime.strptime(s, '%Y-%m-%d')


来源:https://stackoverflow.com/questions/50133185/normalizing-string-to-date-in-cerbrus

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!