首页 > 解决方案 > 如何检查棉花糖模式的日期时间字段是否小于今天的日期?

问题描述

我有一个接受POST方法的端点。POST正文包含DateTime格式为 -的字段"%Y-%m-%d %H:%MZ"。我需要验证该日期时间是否小于 UTC 中的当前日期时间。我Marshmallow用来验证请求正文。

run_datetime = fields.DateTime(format="%Y-%m-%d %H:%MZ")

这种情况下是否有任何内置验证器来验证DateTime字段。或者我应该为此编写一个自定义函数来run_datetime与今天的UTC's datetime.

标签: pythonpython-3.xdatetimemarshmallowflask-marshmallow

解决方案


没有内置的验证器可以解决您手头的特定问题,请在此处查看可用的验证器。虽然,定义您自己的验证器非常简单,但对于您的特定情况:fields.Datetime将接受一个名为的参数,该参数validate可以接受一个返回布尔值的函数。例如,我在这里快速定义了一个 lambda 来验证日期时间是否比“现在”更新:

from datetime import datetime
from marshmallow import Schema, fields

NOW = datetime(2020, 11, 23, 14, 23, 0, 579974)

class User(Schema):
    id = fields.Integer(required=True)
    name = fields.String(required=True)
    # Define an arbitrary datetime here like NOW or just use datetime.now()
    date_created = fields.DateTime(required=True, validate=lambda x: x > NOW)

# This will succeed
User().load(dict(
    id=10,
    name="Test",
    # Note that this date is more recent than previously defined NOW
    date_created="2020-11-23T14:24:40.224965",
))
#{'date_created': datetime.datetime(2020, 11, 23, 14, 24, 40, 224965),
# 'id': 10,
# 'name': 'Test'}

# While this will fail
User().load(dict(
    id=10,
    name="Test",
    # Here the date is one month behind than NOW
    date_created="2020-10-23T14:24:40.224965",
))
# ValidationError: {'date_created': ['Invalid value.']}

推荐阅读