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 JavaScriptDate.parse(), REST APIs, anddatetime.fromisoformat().- Furthermore,
default=strsilently converts every unsupported object (including functions, database cursors, or broken objects) into<function foo at 0x...>, whereas a customjson_serialhelper catches unexpected types immediately by raisingTypeError.
- Always raise
TypeErrorfor unhandled types inside a customdefault=callback:- If your custom
defaultfunction returnsNoneinstead of raisingTypeErrorfor unrecognized objects,json.dumps()will silently serialize unknown objects as JSONnull!
- If your custom
datetimeis a subclass ofdate(isinstance(dt, date)isTrue):- Checking
isinstance(obj, (datetime, date))works cleanly for both becausedatetime.isoformat()includes the time and timezone offset whiledate.isoformat()outputsYYYY-MM-DD. If you handledatetimeanddateseparately, checkdatetimebeforedate.
- Checking
- Serialize
datetimeas Unix epoch integers/floats instead of strings (if required by an API):- Replace
obj.isoformat()withint(obj.timestamp())(seconds) orint(obj.timestamp() * 1000)(milliseconds)—making sure naivedatetimeobjects are timezone-aware UTC first (obj.replace(tzinfo=timezone.utc).timestamp()).
- Replace
- Web frameworks & validation libraries (FastAPI, Pydantic, Flask, Pandas):
- Pydantic v2:
model.model_dump(mode="json")ormodel.model_dump_json()automatically convertsdatetimeanddatefields to ISO-8601 strings. - Pandas
Timestamp/NaT:pd.Timestampis a subclass ofdatetime, so.isoformat()works—except for missingpd.NaT, whose.isoformat()returns"NaT"(checkpd.isna(obj)first and returnNoneso it becomes JSONnull).
- Pydantic v2:
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. |
You must log in or register to comment.
