【问题标题】:Python json schema formatchecker not validating valid datetime stringsPython json模式格式检查器未验证有效的日期时间字符串
【发布时间】:2019-07-31 10:04:09
【问题描述】:

我正在使用有效的日期时间字符串使用 JSON 模式格式检查器在我的数据中进行验证,但它没有验证这种有效的日期时间格式并且失败并出现以下错误:

jsonschema.exceptions.ValidationError: '2013-09-16T15:40:16.21211' is not a 'date-time'

我的代码:

import jsonschema
import json 

data = {"timestamp": "2013-09-16T15:40:16.21211"}

schema ="""{
    "type":"object",
    "$schema": "http://json-schema.org/draft-03/schema",
    "id": "http://jsonschema.net",
    "required":true,
    "properties":{
        "timestamp": { 
            "format" :"date-time",
            "type":"string",
            "required" :false
        }
     }}"""

jsonschema.validate(data,json.loads(schema),format_checker=jsonschema.FormatChecker())

【问题讨论】:

    标签: python datetime jsonschema


    【解决方案1】:

    date-time 验证器 requires the format(“日期和时间格式名称源自 RFC 3339,第 5.6 节”)以符合 RFC3339 中指定的内容:

    date-fullyear   = 4DIGIT
    date-month      = 2DIGIT  ; 01-12
    date-mday       = 2DIGIT  ; 01-28, 01-29, 01-30, 01-31 based on 
                              ; month/year
    time-hour       = 2DIGIT  ; 00-23
    time-minute     = 2DIGIT  ; 00-59
    time-second     = 2DIGIT  ; 00-58, 00-59, 00-60 based on leap second
                              ; rules
    time-secfrac    = "." 1*DIGIT
    time-numoffset  = ("+" / "-") time-hour ":" time-minute
    time-offset     = "Z" / time-numoffset
    
    partial-time    = time-hour ":" time-minute ":" time-second
                     [time-secfrac]
    full-date       = date-fullyear "-" date-month "-" date-mday
    full-time       = partial-time time-offset
    
    date-time       = full-date "T" full-time
    

    规范的full-time 部分需要指定time-offset,即您必须在日期时间之后添加Z 以表示时间为UTC,或者您必须添加显式偏移量(即 +0100 等)。

    【讨论】:

    • 我在我的架构中使用日期时间格式,它是全日期“T”全职
    • 我明白你在说什么,要么在末尾添加 Z,要么显式偏移。谢谢
    猜你喜欢
    • 2015-07-23
    • 2019-04-16
    • 1970-01-01
    • 2021-07-22
    • 2017-03-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-29
    相关资源
    最近更新 更多