Pydantic: Use datetime with format 'YYYY-MM-DD'

Created on 24 Apr 2019  路  1Comment  路  Source: samuelcolvin/pydantic

Hi, I'd like to use the a datetime object (not date) with input string format YYYY-MM-DD but it is not supported. What would be the best way to obtain this behavior? Do I need to make a custom data type? Thanks

question

Most helpful comment

use a validator:

class MyModel(BaseModel):
  foobar: datetime

  @validator('foobar', pre=True)
  def parse_foobar(cls, v):
    if isinstance(v, str):
      return datetime.strptime....  # maybe needs try/except
    return v

>All comments

use a validator:

class MyModel(BaseModel):
  foobar: datetime

  @validator('foobar', pre=True)
  def parse_foobar(cls, v):
    if isinstance(v, str):
      return datetime.strptime....  # maybe needs try/except
    return v
Was this page helpful?
0 / 5 - 0 ratings

Related issues

krzysieqq picture krzysieqq  路  3Comments

ashears picture ashears  路  3Comments

dmontagu picture dmontagu  路  3Comments

vvoody picture vvoody  路  3Comments

ashpreetbedi picture ashpreetbedi  路  3Comments