1
from datetime import datetime, timezone
3
from fastapi import FastAPI
4
from fastapi.testclient import TestClient
5
from pydantic import BaseModel
7
from .utils import needs_pydanticv1, needs_pydanticv2
12
from pydantic import field_serializer
14
class ModelWithDatetimeField(BaseModel):
17
@field_serializer("dt_field")
18
def serialize_datetime(self, dt_field: datetime):
19
return dt_field.replace(microsecond=0, tzinfo=timezone.utc).isoformat()
22
model = ModelWithDatetimeField(dt_field=datetime(2019, 1, 1, 8))
24
@app.get("/model", response_model=ModelWithDatetimeField)
28
client = TestClient(app)
30
response = client.get("/model")
31
assert response.json() == {"dt_field": "2019-01-01T08:00:00+00:00"}
37
class ModelWithDatetimeField(BaseModel):
42
datetime: lambda dt: dt.replace(
43
microsecond=0, tzinfo=timezone.utc
48
model = ModelWithDatetimeField(dt_field=datetime(2019, 1, 1, 8))
50
@app.get("/model", response_model=ModelWithDatetimeField)
54
client = TestClient(app)
56
response = client.get("/model")
57
assert response.json() == {"dt_field": "2019-01-01T08:00:00+00:00"}