简体   繁体   中英

Python pydantic validate dates

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM