My question is pretty simple and I'm surprised no one has asked it so far:
How can I validate dates in pydantic?
For example, I only want to accept dates in the range 1980.1.1-2000.1.1.
validator for datetime field is what you want. You can use it as following:
from pydantic import BaseModel, validator
from datetime import datetime
class DModel(BaseModel):
dt: datetime
@validator("dt")
def ensure_date_range(cls, v):
if not datetime(year=1980, month=1, day=1) <= v < datetime(year=2000, month=1, day=1):
raise ValueError("Must be in range")
return v
DModel.parse_obj({"dt": "1995-01-01T00:00"})
DModel.parse_obj({"dt": "2001-01-01T00:00"}) # validation error
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With