Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Unpacking str dict value into datetime attribute of an object in a nice way

I have a pydantic class like

class MyClass(BaseModel):
    base: str
    success: bool
    date: datetime

I also have a dict like

dict = {
    "base": "abc",
    "success": True,
    "date": "2023-04-30"
}

So I want to do something like obj = MyClass(**dict) but also convert str "date" from dict into datetime "date" of the obj automatically

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

How to do that in a clean and nice way?

>Solution :

Use a validator to transform the value before it gets assigned to the date field. In the follow code will transform the date into a format supported by Pydantic:

from pydantic import BaseModel, validator
from datetime import datetime

class MyClass(BaseModel):
    base: str
    success: bool
    date: datetime

    @validator('date', pre=True)
    def validate_date(cls, v):
        return f'{v}T00:00'


example = MyClass(**{
    "base": "abc",
    "success": True,
    "date": "2023-04-30"
})

print(example)

Running the above code will output:

base='abc' success=True date=datetime.datetime(2023, 4, 30, 0, 0)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading