How do you fix "TypeError: Object of type datetime is not JSON serializable" in Python? | A1Lab@MZeeshanM to PythonEnglish • 3 days ago

How do you fix "TypeError: Object of type datetime is not JSON serializable" in Python?

message-square
0

Pass default=str to json.dumps() / json.dump() for a quick ISO-formatted string fallback (json.dumps(data, default=str)), or pass a custom default serializer function calling .isoformat() on datetime.datetime and datetime.date objects (default=lambda obj: obj.isoformat() if isinstance(obj, (datetime, date)) else ...) so timestamps serialize into clean RFC-3339 / ISO-8601 strings without mutating your source dictionary.

Basic Example

from datetime import date, datetime, timezone
import json

payload = {
    "event": "user_login",
    "created_at": datetime(2026, 11, 29, 12, 17, 0, tzinfo=timezone.utc),
    "expires_on": date(2026, 12, 31),
}

# 1. Recommended (strict, type-safe ISO-8601 serializer):
def json_serial(obj: object) -> str:
    if isinstance(obj, (datetime, date)):
        return obj.isoformat()
    raise TypeError(f"Object of type {type(obj).__name__} is not JSON serializable")

print(json.dumps(payload, default=json_serial))
# Output: {"event": "user_login", "created_at": "2026-11-29T12:17:00+00:00", "expires_on": "2026-12-31"}

# 2. Quick one-liner fallback (calls str(obj) on any non-standard type):
print(json.dumps(payload, default=str))
# Output: {"event": "user_login", "created_at": "2026-11-29 12:17:00+00:00", "expires_on": "2026-12-31"}

Key Details & Edge Cases

  • default=json_serial (.isoformat()) vs. default=str:
    • str(datetime(...)) separates date and time with a space ("2026-11-29 12:17:00+00:00"), whereas .isoformat() produces the standard ISO-8601 "T" separator ("2026-11-29T12:17:00+00:00") expected by JavaScript Date.parse(), REST APIs, and datetime.fromisoformat().
    • Furthermore, default=str silently converts every unsupported object (including functions, database cursors, or broken objects) into <function foo at 0x...>, whereas a custom json_serial helper catches unexpected types immediately by raising TypeError.
  • Always raise TypeError for unhandled types inside a custom default= callback:
    • If your custom default function returns None instead of raising TypeError for unrecognized objects, json.dumps() will silently serialize unknown objects as JSON null!
  • datetime is a subclass of date (isinstance(dt, date) is True):
    • Checking isinstance(obj, (datetime, date)) works cleanly for both because datetime.isoformat() includes the time and timezone offset while date.isoformat() outputs YYYY-MM-DD. If you handle datetime and date separately, check datetime before date.
  • Serialize datetime as Unix epoch integers/floats instead of strings (if required by an API):
    • Replace obj.isoformat() with int(obj.timestamp()) (seconds) or int(obj.timestamp() * 1000) (milliseconds)—making sure naive datetime objects are timezone-aware UTC first (obj.replace(tzinfo=timezone.utc).timestamp()).
  • Web frameworks & validation libraries (FastAPI, Pydantic, Flask, Pandas):
    • Pydantic v2: model.model_dump(mode="json") or model.model_dump_json() automatically converts datetime and date fields to ISO-8601 strings.
    • Pandas Timestamp / NaT: pd.Timestamp is a subclass of datetime, so .isoformat() works—except for missing pd.NaT, whose .isoformat() returns "NaT" (check pd.isna(obj) first and return None so it becomes JSON null).

Comparison of datetime JSON Serialization Approaches

Approach Output Format Catches Unexpected Non-Serializable Types? Preserves ISO-8601 "T" Separator? Best Used When
json.dumps(data, default=json_serial) (Recommended) "2026-11-29T12:17:00+00:00" Yes (raises TypeError on unknown types) Yes (.isoformat()) Production APIs, logs, and payloads requiring strict RFC-3339 / ISO-8601 timestamps.
json.dumps(data, default=str) "2026-11-29 12:17:00+00:00" No (stringifies anything via str()) No (uses space separator) Quick debugging, scripts, or logging where any readable string representation suffices.
json.JSONEncoder Subclass (cls=DateTimeEncoder) "2026-11-29T12:17:00+00:00" Yes (super().default(obj)) Yes (.isoformat()) Reusable encoder classes passed into frameworks (Flask / json.dump(..., cls=...)).
model.model_dump_json() (Pydantic v2) "2026-11-29T12:17:00Z" Yes (validated schema) Yes FastAPI / Pydantic applications already modeling payloads with typed schemas.