如何在Python Cerberus中将字符串强制转换为日期时间? [英] How to coerce string to datetime in Python Cerberus?

查看:68
本文介绍了如何在Python Cerberus中将字符串强制转换为日期时间?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将字符串强制转换为日期,以便它可以验证日期数据类型,但仍返回 False :

I'm trying to coerce string as date so it can validate date data type, but it still returns False:

from cerberus import Validator
from datetime import datetime

v = Validator()
v.schema = {'start_date': {'type': 'date','coerce':datetime.date}}
v.validate({'start_date': '2017-10-01'})
>>> False

我尝试使用整数,它可以工作.我不确定为什么日期转换不起作用:

I have tried to use the integer and it works. I'm not sure why date conversion is not working:

v = Validator()
v.schema = {'amount': {'type': 'integer','coerce': int}}
v.validate({'amount': '2'})
>>> True

任何帮助将不胜感激.

推荐答案

恐怕单独 datetime.date 不会将字符串转换为日期值.如果您在REPL中尝试过,那么您将得到:

I am afraid that datetime.date alone won't convert a string to a date value. If you try that in the REPL this is what you get:

>>> datetime.date('2017-10-01')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: descriptor 'date' requires a 'datetime.datetime' object but received a 'str'

尝试这样的方法:

from cerberus import Validator
from datetime import datetime

v = Validator()
to_date = lambda s: datetime.strptime(s, '%Y-%m-%d')
v.schema = {'start_date': {'type': 'datetime','coerce': to_date}}
v.validate({'start_date': '2017-10-01'})
>>> True

这篇关于如何在Python Cerberus中将字符串强制转换为日期时间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆