← Back to FastAPI, page 5

fastapi-0083 · Medium mid

How do you handle datetimes with time zones, Decimals and custom JSON encoding correctly in Pydantic v2 and FastAPI?

Use timezone-aware datetimes (AwareDatetime type, or store UTC) so comparisons are unambiguous, accept ISO 8601 strings with offsets, and convert to the user's zone only at the edges. Use Decimal for money with max_digits and decimal_places constraints; Pydantic v2 serialises Decimal as a JSON string through a response model, which preserves exactness. Customise output with field_serializer or Annotated serializers, and note that naive datetimes serialise without an offset.

Full answer

Datetimes:

  • A naive datetime has no zone (2026-12-04T10:00:00); an aware one carries an offset (+05:30) or Z. Mixing them raises TypeError when compared.
  • Pydantic types: datetime (either), AwareDatetime (offset required), NaiveDatetime. For APIs, require AwareDatetime and normalise to UTC in your service: value.astimezone(timezone.utc).
  • JSON output is ISO 8601 with offset (2026-12-04T04:30:00Z for UTC). Clients convert to local time.
  • Store timestamps in UTC (timestamptz in PostgreSQL); keep the user's IANA zone name (Asia/Kolkata) separately if you need local-time features. Use zoneinfo.ZoneInfo, not fixed offsets, for daylight-saving aware conversion.
  • "Dates" like a birthday are date, not datetime, to avoid zone shifts.

Decimals:

  • Decimal avoids binary float errors (0.1 + 0.2). Constrain: Field(max_digits=10, decimal_places=2).
  • Input accepts JSON numbers or strings; sending strings ("199.90") avoids client-side float rounding.
  • Output through a response model is a JSON string by default ("199.90"), which JavaScript clients must parse; a plain dict without a model passes through jsonable_encoder and becomes a float, losing exactness.
  • Do arithmetic with Decimal and quantise explicitly (.quantize(Decimal("0.01"), ROUND_HALF_UP)) at defined points.
  • Store as NUMERIC in the database; many ORMs map it to Decimal.

Custom encodings:

  • Annotated[Decimal, PlainSerializer(lambda v: float(v), return_type=float)] forces numbers (accepting precision loss).
  • field_serializer formats a datetime for display.
  • ConfigDict(ser_json_timedelta="iso8601", ser_json_bytes="base64") and json_encoders (deprecated in v2) control other types.

Test around month ends, leap days and DST changes, and always include the offset in test data.

python
from datetime import datetime, timezone
from decimal import ROUND_HALF_UP, Decimal
from zoneinfo import ZoneInfo

from fastapi import FastAPI
from fastapi.testclient import TestClient
from pydantic import AwareDatetime, BaseModel, Field, ValidationError

app = FastAPI()


class Payment(BaseModel):
    paid_at: AwareDatetime
    amount: Decimal = Field(max_digits=10, decimal_places=2, gt=0)


class Receipt(BaseModel):
    paid_at_utc: datetime
    amount: Decimal


@app.post("/payments", response_model=Receipt)
def pay(p: Payment):
    gst = (p.amount * Decimal("0.18")).quantize(Decimal("0.01"), rounding=ROUND_HALF_UP)
    return {"paid_at_utc": p.paid_at.astimezone(timezone.utc), "amount": p.amount + gst}


c = TestClient(app)
r = c.post("/payments", json={"paid_at": "2026-12-04T10:00:00+05:30", "amount": "199.90"})
print(r.status_code, r.text)
print(c.post("/payments", json={"paid_at": "2026-12-04T10:00:00", "amount": "199.90"}).json()["detail"][0]["type"])
print(c.post("/payments", json={"paid_at": "2026-12-04T10:00:00Z", "amount": "10.999"}).json()["detail"][0]["type"])

print(0.1 + 0.2, Decimal("0.1") + Decimal("0.2"))
local = datetime(2026, 12, 4, 10, 0, tzinfo=ZoneInfo("Asia/Kolkata"))
print(local.isoformat(), local.astimezone(timezone.utc).isoformat(), local.astimezone(ZoneInfo("America/New_York")).isoformat())
try:
    datetime(2026, 1, 1) < local
except TypeError as exc:
    print("naive vs aware:", exc)

Standalone script. Run it with `python file.py`; it calls the app through TestClient, so no server is needed. Output (ran twice with identical results; Python 3.13.5, FastAPI 0.165.1, Pydantic 2.14.4, Starlette 1.10.0, SQLAlchemy 2.1.9, httpx 0.29.0): 200 {"paid_at_utc":"2026-12-04T04:30:00Z","amount":"235.88"} timezone_aware decimal_max_places 0.30000000000000004 0.3 2026-12-04T10:00:00+05:30 2026-12-04T04:30:00+00:00 2026-12-03T23:30:00-05:00 naive vs aware: can't compare offset-naive and offset-aware datetimes

Key points

  • Aware datetimes with offsets; store UTC, convert at the edges
  • AwareDatetime rejects naive input
  • Decimal for money with max_digits and decimal_places
  • Through a response model Decimal becomes a string; bare dicts give floats
  • Use serializers for custom output; avoid deprecated json_encoders

Common mistakes

  • Using naive datetimes in an API and guessing the zone later
  • Using float for currency
  • Storing local times without a zone
  • Returning Decimal in a bare dict and getting a float
  • Using fixed offsets instead of IANA zones for daylight saving

Follow-ups

  • How do you store a user's preferred time zone?
  • How do you format Decimal as a number in JSON when needed?
  • What breaks around daylight-saving changes?

Tips

  • State UTC at the edges
  • Say Decimal with constraints
  • Mention serialization differences