Search code examples
pythondatedatetimefastapipydantic

Custom date format in FastAPI model


I have a date type of the format 15-Jul-1996. And I am trying to define a Pydantic model to use for input data validation in a FastAPI application as such:

from pydantic import BaseModel
from datetime import date

class Profile(BaseModel):
    name: str
    DOB: date  # type of 15-Jul-1996
    gender: str

Is there a way to constrain the DOB to that particular format? I can't seem to find a way to do that in the Pydantic docs.

The attempt above is not quite what I want as it constrains to 05-07-2023.


Solution

  • Try this. You can use @validator

    from pydantic import BaseModel, validator
    from datetime import datetime
    
    class Profile(BaseModel):
        name: str
        DOB: str  # change this to str
        gender: str
    
        @validator('DOB')
        def parse_dob(cls, v):
            return datetime.strptime(v, '%d-%b-%Y').date()  # convert string to date