【问题标题】:How to use min value with type datetime in Cerberus?如何在 Cerberus 中使用日期时间类型的最小值?
【发布时间】:2022-02-17 13:19:12
【问题描述】:

我想在 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

【问题讨论】:

    标签: python date datetime validation cerberus


    【解决方案1】:

    您的方法不是错误的,只是缺少一个决定性的组成部分 - 即说明 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
    

    【讨论】:

      猜你喜欢
      • 2021-12-23
      • 1970-01-01
      • 2021-05-30
      • 1970-01-01
      • 2015-12-12
      • 1970-01-01
      • 2021-04-26
      • 1970-01-01
      • 2013-09-09
      相关资源
      最近更新 更多