TypeError: Object of type datetime is not JSON serializable
Youβre trying to convert a Python object to JSON that json.dumps() doesnβt know how to handle.
Why this happens
Pythonβs json module only serializes basic types: str, int, float, bool, list, dict, and None. Any other type β datetime, set, Decimal, UUID β raises this error because the serializer doesnβt know how to represent them as JSON.
Fix 1: Convert to a serializable type
import json
from datetime import datetime
data = {"created": datetime.now()}
# β datetime isn't serializable
json.dumps(data)
# β
Convert to string first
data = {"created": datetime.now().isoformat()}
json.dumps(data)
Fix 2: Custom encoder
class CustomEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, datetime):
return obj.isoformat()
if isinstance(obj, set):
return list(obj)
return super().default(obj)
json.dumps(data, cls=CustomEncoder)
Fix 3: Use default parameter
json.dumps(data, default=str) # Converts everything to string
Alternative solution: Use Pydantic for complex objects
Pydantic models handle datetime, UUID, etc. natively:
from pydantic import BaseModel
class Event(BaseModel):
name: str
created: datetime
print(Event(name="deploy", created=datetime.now()).model_dump_json())
Prevention
- Build a project-wide custom encoder early and reuse it across your codebase.
- Convert ORM query results to dicts or Pydantic models before serializing.
Related: Python cheat sheet Β· Python complete guide Β· Pip Install Error Fix Β· Unexpected End of JSON Input Fix