python - 如何检查棉花糖模式的日期时间字段是否小于今天的日期?
问题描述
我有一个接受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
.
解决方案
没有内置的验证器可以解决您手头的特定问题,请在此处查看可用的验证器。虽然,定义您自己的验证器非常简单,但对于您的特定情况: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.']}
推荐阅读
- parallel-processing - 在 talend 上对同一个作业执行 2 个文件观察程序
- python - 为不同大小制作循环定义
- python - Python:将代码应用于整个数据框列
- c - C - 从不同的函数访问结构变量
- solr - 为什么 solr-node 查询给出错误的文档版本号?
- java - 获取 Java mysql SQL 语法错误,但我的查询似乎正常
- python-3.x - Python Adal - 无法使用访问令牌检索 Outlook 邮件
- python - 如何使用烧瓶从网页导入 csv 文件?
- php - 更改输出变量 MySQL 查询
- javascript - 如何在 React-Native 中转换这个对象?