5

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 to annotate startTime as int. I would like to annotate it as UnixMicrotime or similar, so that Pydantic also parses it to datetime (and converts a datetime back to UnixMicrotime when serializing). Is that possible?

Minimal Example

import json
from pydantic import BaseModel


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


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

gives

protocol='http' isPublic=False startTime=1607586354631

but I would like it to be:

protocol='http' isPublic=False startTime=2020-12-10T08:45:54
alex_noname
  • 26,459
  • 5
  • 69
  • 86
Martin Thoma
  • 124,992
  • 159
  • 614
  • 958

1 Answers1

6

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}
alex_noname
  • 26,459
  • 5
  • 69
  • 86