date and datetime validation using cerberus for field specific date format

43 views Asked by At

I am using cerberus for data validation. We are sourcing data from different source systems. some systems have different date formats. As the coerce function only gets a value argument, no way to provide a format based on the field name. Is there a way around it?

The "validator" rule, which allows external functions to validate field values is useful. because it accepts (field, value, error) argument. so we can maintain an external dictionary with key = field name and value = date format and using dictionary lookup we can get the appropriate date format and do date conversion. but then the returned value is not in date time format. only value returned via the coerce function is in Python date format.

e.g.

dict = { 'field1' : '%Y%m%d', 'field2' : '%d%m%Y'} # see difference in date format

how to use Cerberus to convert above 2 fields in date format ?

schema = { 'field1' : { 'type' : date },
           'field2' : { 'type' : date }
}

data = { 'field1', '20220323', 'field2', '22032022'}

from cerberus import Validator 
v = Validator(normalize=True)
v = v.validate(data,schema)
print(v.document) #This should printfields in pythonn date format?

I tried using the validator function, which is helpful for dynamically detecting date type, based on field name but its not returning value in python date format.

e.g.

type here
dict = { 'field1' : '%Y%m%d', 'field2' : '%d%m%Y'} # see difference in date format

def to_date(field, value,error):
format = dict.get(field,'"%Y%m%d')
return value.strptime(format)

schema = { 'dt' : { 'type' : 'date', 'validator' : to_date }
from cerberus import validator
data = { 'dt' : '20220312'}

v = Validator(normalize=True)
v.validate(data,schema)
print(v.document)

v.document is not printing date in DateTime.date format?

looks like 'coerce' and 'validator' can not be used at the same time.

please advise, on how to use date format while validating the date, return value should be in Python date format.your text

I am using cerberus 1.2 version

0

There are 0 answers