Skip to content

Instantly share code, notes, and snippets.

@antibagr
Created August 5, 2021 16:58
Show Gist options
  • Save antibagr/40a6e07e1be0a84aa45469ac6a99b585 to your computer and use it in GitHub Desktop.
Save antibagr/40a6e07e1be0a84aa45469ac6a99b585 to your computer and use it in GitHub Desktop.
FastAPI Custom Datetime Format (ISO 8601)
import asyncio
from datetime import datetime
import pytest
from fastapi import FastAPI
from starlette.testclient import TestClient
from pydantic import BaseModel
class CustomDatetime(BaseModel):
dt_field: datetime
class Config:
json_encoders = {
datetime: lambda dt: dt.strftime('%Y-%m-%dT%H:%M:%SZ'),
}
app = FastAPI()
@pytest.fixture(autouse=True)
def get_event_loop() -> None:
asyncio.set_event_loop(asyncio.new_event_loop())
@app.get('/model', response_model=CustomDatetime)
def get_model():
return CustomDatetime(dt_field=datetime(2019, 1, 1, 8))
def test_datetime_custom_format():
with TestClient(app) as client:
response = client.get('/model')
assert response.json() == {'dt_field': '2019-01-01T08:00:00Z'}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment