使用JSON模式将日期/时间字符串解析为datetimes

2024-08-31 09:00:49 发布

您现在位置:Python中文网/ 问答频道 /正文

我可以使用jsonschema来指定值是JSON对象中的有效日期,如下所示:

import jsonschema

schema = {'type': 'object', 'properties': {'dt': {'type': 'string', 'format': 'date'}}}

# fine
jsonschema.validate({'dt': '2017-01-01'}, schema, format_checker=jsonschema.FormatChecker())

# jsonschema.exceptions.ValidationError: 'not a date' is not a 'date'
jsonschema.validate({'dt': 'not a date'}, schema, format_checker=jsonschema.FormatChecker())

但是,这使dt的值保持不变,仍然是字符串。我需要将日期/时间转换为datetime.date/datetime.datetime实例,有没有一种方法可以在给定一个JSON模式(使用jsonschema或任何其他库)的情况下自动执行此操作?在

理想情况下,我想要这样的东西:

^{pr2}$

我有一个包含许多JSON文档的大型项目,这些文档可能非常大,并且有许多层次的嵌套,因此它不像简单地自己查找键并在对象验证后处理它们那样简单。在


Tags: 对象文档jsonformatdatetimedateschematype