Skip to content Skip to sidebar Skip to footer

Can I Create A Unix Time Type Which Automatically Converts To Datetime In Pydantic?

I receive a JSON response like with a unix timestamp, e.g.: {'protocol': 'http', 'isPublic': false, 'startTime': 1607586354631} The simplest way to read this data with Pydantic is

Solution 1:

You could annotate it as datetime to parse it, and add custom json_encoder for serializing datetime as unix time. Sample:

import json
from datetime import datetime

from pydantic import BaseModel

json_str = """{"protocol": "http", "isPublic": false, "startTime": 1607586354631}"""
data_dict = json.loads(json_str)


class Data(BaseModel):
    protocol: str
    isPublic: bool
    startTime: datetime


data = Data.parse_obj(data_dict)
print(data.json())


class DataWithUnixTime(BaseModel):
    protocol: str
    isPublic: bool
    startTime: datetime

    class Config:
        json_encoders = {
            datetime: lambda v: v.timestamp(),
        }


data = DataWithUnixTime.parse_obj(data_dict)
print(data.json())
{"protocol": "http", "isPublic": false, "startTime": "2020-12-10T07:45:54.631000+00:00"}
{"protocol": "http", "isPublic": false, "startTime": 1607586354.631}

Post a Comment for "Can I Create A Unix Time Type Which Automatically Converts To Datetime In Pydantic?"