Validate datetime value using python jsonschema
Asked Answered
I

4

8

I'm using jsonschema to validate my python dictionary. I' trying to validate a datetime value but I'm not sure how to do it.

Here's what I have so far, which results in an error because jsonschema doesn't have a datetime type:

order = {
    "name": "shirt",
    "order_datetime": datetime.datetime(2018, 1, 18)
}

schema = {
    "title": "Order",
    "type": "object",
    "required": ["name", "order_datetime"],
    "properties": {
        "name": {
            "type": "string"
        },
        "order_datetime": {
            "type": "datetime"
        }
    }
}

from jsonschema import validate
validate(order, schema)

The error is jsonschema.exceptions.SchemaError: 'datetime' is not valid under any of the given schemas. How can I validate this correctly?

Incommunicado answered 6/9, 2018 at 18:46 Comment(4)
The docs suggest that it's spelled with a dash 'date-time'. And looking at one of the schemas it's described as "a valid date-time string", not a datetime instance.Foreandafter
@StevenRumbalski I need to validate a datetime instanceIncommunicado
Follow the first link on my comment to @sobek's answer which shows how to extend types. Instead of extending number you would extend date-time.Foreandafter
If you are not actually planning to dump to JSON and just want to validate your dictionary use schema.Foreandafter
L
14

Here's how to properly validate with a native Python datetime object. Assumes you have jsonschema 3.x:

from datetime import datetime
import jsonschema

def validate_with_datetime(schema, instance):
  BaseVal = jsonschema.Draft7Validator

  # Build a new type checker
  def is_datetime(checker, inst):
    return isinstance(inst, datetime)
  date_check = BaseVal.TYPE_CHECKER.redefine('datetime', is_datetime)

  # Build a validator with the new type checker
  Validator = jsonschema.validators.extend(BaseVal, type_checker=date_check)

  # Run the new Validator
  Validator(schema=schema).validate(instance)
Leatherman answered 26/8, 2019 at 22:31 Comment(0)
C
4

Once you add rfc3339-validator or strict-rfc3339 to project dependencies (the first one is much more accurate as I can see), jsonschema.FormatChecker class will register the date-time format validator. So the code will be as simple, as it should be:

from jsonschema import (
    Draft7Validator,
    FormatChecker,
)

schema = {
  "$schema": "http://json-schema.org/draft-07/schema#",
  "type": "object",
  "properties": {
    "datetime": {
      "type": "string",
      "format": "date-time"
    }
  }
}

validator = Draft7Validator(schema, format_checker=FormatChecker())
data_samples = [
    {'datetime': '2021-01-01T00:01:02.003+01:00'},
    {'datetime': '2021-01-01'},
]
assert validator.is_valid(data_samples[0]) is True
assert validator.is_valid(data_samples[1]) is False

You can have a look at other possible to use formats, libraries they require, and other tips at jsonschema documentation page.

Clayborne answered 13/7, 2021 at 7:33 Comment(0)
E
1

With help of @speedplane's answer, I was able to get the type checker working for my case of order_datetime.

order = {
    "name": "shirt",
    "order_datetime": "2019-09-13-22.30.00.000000"
}

schema = {
    "title": "Order",
    "type": "object",
    "required": ["name", "order_datetime"],
    "properties": {
        "name": {
            "type": "string"
        },
        "order_datetime": {
            "type": "orderdatetime"
        }
    }
}

Python code

import jsonschema
def validate_with_datetime(schema, instance):
  BaseVal = jsonschema.Draft7Validator
  # Build a new type checker
  def is_datetime(checker, inst):
     try:
        datetime.datetime.strptime(inst, '%Y-%m-%d-%H.%M.%S.%f')
        return True
     except ValueError:
        return False
  date_check = BaseVal.TYPE_CHECKER.redefine(u'orderdatetime', is_datetime)
  

  # Build a validator with the new type checker
  Validator = jsonschema.validators.extend(BaseVal, type_checker=date_check)

  # Run the new Validator
  Validator(schema=schema).validate(instance)

validate_with_datetime(schema, order)

But while exploring jsonschema library, I came across FormatChecker(). Can't we use jsonschema.FormatChecker() to validate the format of datetime type property ?

@speedplane Can you post an example how to use FormatChecker() ?

Esculent answered 15/11, 2019 at 14:33 Comment(0)
C
0

Just pass your date time value as a str .

schema={"type":'object',
        "required":['date'],
        "properties":{"date":{'type':'string',format:'date-time'}}})

validate({'date':str(datetime.datetime(2023, 7, 27, 10, 33, 26, 569990))},schema)
Corporation answered 27/7, 2023 at 12:52 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.