如何在 Cerberus 中使用日期时间类型的最小值?

How to use min value with type datetime in Cerberus?

我想在 Cerberus 的 datetime 类型中验证一个值大于或等于 01/01/1900 的字段,但不是这样工作的:

from cerberus import Validator 
from datetime import datetime
    
v = Validator()
schema = {
    "birthdate": {
        "type": "datetime",
        "required": True,
        "min": datetime(1900, 1, 1)
    }
}
document_valid = {'birthdate': '05/03/1900'}
document_invalid = {'birthdate': '05/03/1800'}

print(v.validate(document_valid, schema)) # I want this True
print(v.validate(document_invalid, schema)) # I want this False

有人能帮帮我吗?

我将此版本用于 Cerberus:Cerberus==1.3.4

您的方法不假,只是缺少一个决定性的组成部分 - 即考虑 date-format

试试这个:

from cerberus import Validator 
from datetime import datetime   

v = Validator()
to_date = lambda s: datetime.strptime(s, '%d/%m/%Y') # date-formatting

schema = {
    "birthdate": {
        "type": "datetime",
        "required": True,
        'coerce': to_date,
        "min": datetime(1900, 1, 1)
    }
}
document_valid = {'birthdate': '05/03/1900'}
document_invalid = {'birthdate': '05/03/1800'}

print(v.validate(document_valid, schema)) # I want this True
print(v.validate(document_invalid, schema)) # I want this False