Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to coerce string to datetime in Python Cerberus?

I'm trying to coerce string as date so it can validate date data type, but it still returns False:

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

I have tried to use the integer and it works. I'm 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.

like image 775
Aryan087 Avatar asked May 02 '18 11:05

Aryan087


1 Answers

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
like image 171
Nicola Iarocci Avatar answered Oct 05 '22 23:10

Nicola Iarocci