Python: Object of type datetime is not JSON serializable
json.dumps only encodes primitives and containers. Convert datetime, Decimal, UUID, set and NumPy values, or add a default hook that stays strict.

Introduction & Quick Summary
TypeError: Object of type datetime is not JSON serializablejson.dumps knows six types: dict, list, tuple, str, int, float, bool and None. Everything else must be converted before encoding, and the error names the first object it could not handle. The object is usually a datetime, Decimal, UUID, set, bytes, a dataclass or a NumPy scalar.
Three fixes, in increasing scope:
- Convert at the boundary —
datetime.isoformat(),str(uuid),float(decimal). - Pass
default=— a function called for any unknown object, applied recursively. - Subclass
JSONEncoder— when the rule must be reused across many call sites.
The choice matters for correctness: default=str makes the error disappear and silently produces values like "Decimal('19.99')" or "<User object at 0x...>", which downstream consumers cannot parse.
| Type in the error | Correct JSON form | Trap |
|---|---|---|
datetime | ISO 8601 string with offset | Naive datetimes lose timezone |
date | YYYY-MM-DD | isoformat() on datetime includes time |
Decimal | String, not float | Money precision loss |
UUID | Canonical hyphenated string | bytes form is not JSON-safe |
set | List, sorted for determinism | Order changes between runs |
bytes | Base64 string | Decoding assumptions |
numpy.int64 | Python int | isinstance(x, int) is false |
| dataclass | dataclasses.asdict | Deep copy of nested values |
Core Mechanics, Signatures & Reproducible Setup
The encoder walks containers recursively and calls the C serializer on leaves. On an unknown leaf it raises TypeError unless default is supplied. default is called once per unknown object and its return value is encoded again, so returning a dict is legitimate; returning another unsupported object re-enters the same failure.
Reproduce the common cases:
import json
from datetime import datetime, timezone
from decimal import Decimal
from uuid import uuid4
payload = {
"id": uuid4(),
"created_at": datetime(2026, 11, 23, 10, 0, tzinfo=timezone.utc),
"amount": Decimal("19.99"),
"tags": {"api", "billing"},
}
json.dumps(payload)
# TypeError: Object of type UUID is not JSON serializableFix explicitly, which keeps every conversion visible in review:
def to_jsonable(value):
return {
"id": str(value["id"]),
"created_at": value["created_at"].isoformat(),
"amount": str(value["amount"]),
"tags": sorted(value["tags"]),
}
json.dumps(to_jsonable(payload))Or centralize with a default hook that refuses to guess:
def json_default(obj):
if isinstance(obj, datetime):
if obj.tzinfo is None:
raise ValueError("naive datetime: attach a timezone before serializing")
return obj.isoformat()
if isinstance(obj, Decimal):
return str(obj)
if isinstance(obj, (set, frozenset)):
return sorted(obj)
if isinstance(obj, bytes):
import base64
return base64.b64encode(obj).decode("ascii")
if hasattr(obj, "isoformat"):
return obj.isoformat()
raise TypeError(f"Unsupported type: {type(obj).__name__}")
json.dumps(payload, default=json_default)Raising on unknown types keeps the contract honest: the next unsupported object fails loudly instead of becoming a string repr.
Key Comparison Table
| Approach | Covers | Reusable | Risk |
|---|---|---|---|
| Explicit conversion | Only what you write | No | Missed nested field |
default=str | Everything | Yes | Unparseable output |
default= function | What it handles | Yes | Silent fallback if too broad |
JSONEncoder subclass | Everything it handles | Yes | Same, plus subclassing cost |
Pydantic model_dump(mode="json") | Model fields | Yes | Requires the model |
orjson with default | Handles datetime natively | Yes | Different library, stricter |
dataclasses.asdict + hook | Dataclasses | Yes | Recurses into all fields |
| Serializer | datetime | Decimal | numpy | NaN allowed |
|---|---|---|---|---|
json | No | No | No | Yes, invalid JSON |
orjson | Yes, UTC-aware | No | Some | No |
simplejson | No | Yes with use_decimal | No | Optional |
| Pydantic v2 | Yes | Yes as string | Partial | Configurable |
Practical Edge Cases, Error Fixes & Deep Dive Code Examples
Case 1: datetime with and without a timezone
from datetime import datetime, timezone
datetime.utcnow().isoformat() # '2026-11-23T01:00:00.123456'
datetime.now(timezone.utc).isoformat() # '2026-11-23T01:00:00.123456+00:00'utcnow() returns a naive datetime; its ISO string has no offset, so clients interpret it in local time. Use datetime.now(timezone.utc) and serialize with .isoformat(). On Python 3.11+, datetime.UTC is an alias for timezone.utc.
def iso_utc(dt: datetime) -> str:
if dt.tzinfo is None:
raise ValueError("naive datetime")
return dt.astimezone(timezone.utc).isoformat().replace("+00:00", "Z")The trailing Z is optional; both forms are valid ISO 8601 and JavaScript's Date parses either.
Case 2: Decimal must not become a float
from decimal import Decimal
import json
json.dumps({"total": float(Decimal("0.1") + Decimal("0.2"))})
# {"total": 0.30000000000000004}For money, serialize as a string and let the consumer use a decimal type:
json.dumps({"total": str(Decimal("0.1") + Decimal("0.2"))})
# {"total": "0.3"}If the consumer requires a number, use orjson with a custom option or round explicitly with a documented scale. Never rely on float(decimal) for currency arithmetic.
Case 3: set ordering changes between processes
json.dumps(sorted({"b", "a", "c"})) # ["a", "b", "c"]
json.dumps(list({"b", "a", "c"})) # order depends on hashingSets of strings are hash-randomized per process unless PYTHONHASHSEED is fixed, so unsorted output makes cached responses and test snapshots unstable. Sort before serializing, or store a list in the first place.
Case 4: dataclasses and nested models
from dataclasses import dataclass, asdict, field
from datetime import datetime, timezone
@dataclass
class Event:
name: str
at: datetime
tags: list[str] = field(default_factory=list)
e = Event("deploy", datetime.now(timezone.utc), ["api"])
json.dumps(asdict(e), default=str)asdict recurses into nested dataclasses but leaves datetime untouched, so the default hook is still required. default=str works here but produces a space-separated datetime format instead of ISO 8601 on some types; prefer the explicit hook.
With Pydantic v2, let the model do it:
class Event(BaseModel):
name: str
at: datetime
tags: list[str] = []
payload = Event(name="deploy", at=datetime.now(timezone.utc)).model_dump(mode="json")
json.dumps(payload)mode="json" converts datetimes, UUIDs and enums to JSON-safe primitives. model_dump() without it returns Python objects and fails at json.dumps.
Case 5: NumPy and pandas scalars
import numpy as np, json
json.dumps({"count": np.int64(5)})
# TypeError: Object of type int64 is not JSON serializablenp.int64 is not a subclass of int on all platforms. Convert explicitly:
def numpy_default(o):
if isinstance(o, np.integer):
return int(o)
if isinstance(o, np.floating):
return float(o)
if isinstance(o, np.ndarray):
return o.tolist()
raise TypeError(type(o).__name__)
json.dumps({"count": np.int64(5)}, default=numpy_default)For DataFrames, df.to_json(orient="records") handles the conversion internally and is less error-prone than serializing df.to_dict().
Case 6: NaN and Infinity produce invalid JSON
json.dumps({"value": float("nan")})
# {"value": NaN} <- not valid JSON per RFC 8259Python's encoder allows these by default. Browsers' JSON.parse rejects the output, and strict parsers in other services fail. Set allow_nan=False to fail at the producer instead of at every consumer:
json.dumps(payload, default=json_default, allow_nan=False)Replace missing numeric values with None before serializing when None is the intended representation.
Common Compilation/Runtime Mistakes & Version Gotchas
default=strin production. It converts every unknown type, including objects whose__str__includes memory addresses, into strings. Bugs move from a loudTypeErrorto a silent contract violation.- Overriding
defaultbut notiterencode. AJSONEncodersubclass that changes container handling must overrideiterencode, not justdefault;defaultis only consulted for leaves. - Circular references. A self-referencing dict raises
ValueError: Circular reference detected, notTypeError. Usecheck_circular=Falseonly when you know the graph is acyclic. ensure_ascii=Trueby default. Non-ASCII text is escaped as\uXXXX; output is valid but larger. Setensure_ascii=Falseand encode UTF-8 explicitly when writing bytes.- Non-string dict keys.
intandfloatkeys are coerced to strings; tuples are rejected withTypeError: keys must be str, int, float, bool or None. Convert keys before encoding. - Pydantic v1 versus v2.
dict()andjson()exist in v1; v2 usesmodel_dump(mode="json"). A v1 tutorial'sjson.dumps(obj.dict())fails on v2 models with nested datetimes, which is this error again.
To inspect a failing payload before it is serialized, format it with the JSON formatter. When the data arrived as CSV, the CSV to JSON converter shows which columns became strings and which stayed unquoted, which explains many Decimal and int mismatches at the source.
Primary references: json documents default, allow_nan and the encoder protocol, and datetime.isoformat defines the string form including the offset.
Official references
primary documentationThe Python documentation that defines the behaviour this guide explains.
Try matching browser tools
All toolsSmall utilities that fit Python work — they run entirely in this browser tab, so nothing you paste leaves your device.
Related Python guides
All Python guidesPython Typer Rich Integration and Progress Bars
python typer rich integration and progress bars: Learn to integrate Rich progress bars into Typer CLI applications, covering track, Progress, dynamic.
Python 3.14 PEP 649: NameError from lazy annotations
Annotations are no longer strings. A NAME only imported under TYPE_CHECKING now raises when FastAPI or Pydantic reads the signature.
asyncpg DuplicatePreparedStatement on PgBouncer and Supabase
asyncpg caches prepared statements per connection while a transaction pooler rotates connections underneath it. The cache setting, pool sizing and retry.
Python Tabulate: Markdown Grid Headers and Alignment
Use Python's tabulate library to format Markdown tables, set custom headers, and control column alignment with pipe and grid formats.
More in Python
All Python guidesThe guides filed next to this one in Python, in library order.