Underoos
Underoos

Reputation: 5180

How to check if a Marshmallow schema's Datetime field is less than today's date?

I have an endpoint that accepts POST method. The POST body contains a DateTime field of format - "%Y-%m-%d %H:%MZ". I need to validate if that datetime is less than current Datetime in UTC. I'm using Marshmallow to validate the request body.

run_datetime = fields.DateTime(format="%Y-%m-%d %H:%MZ")

Are there any inbuilt validators for this case to validate DateTime field. Or should I be writing a custom function for this to compare the run_datetime with today's UTC's datetime.

Upvotes: 0

Views: 4403

Answers (2)

RAY Courtney
RAY Courtney

Reputation: 1

Use the range validator.

import datetime
import marshmallow.validate

run_datetime = fields.DateTime(
   format="%Y-%m-%d %H:%MZ", 
   validate=marshmallow.validate.Range(min=datetime.datetime.now())))

Upvotes: 0

Loscil94
Loscil94

Reputation: 83

There is no built-in validator that can solve your particular issue at hand, take a look at the available validators here. Although, defining your own validator is trivially easy, for your particular case: fields.Datetime will accept an argument named validate which can take a function that returns a bool. For example, I quickly defined a lambda here to validate if the datetime is more recent than "now":

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.']}

Upvotes: 3

Related Questions