Datetime Serialisation
JSON does not natively support datetime. Use ISO 8601 strings for APIs and serialise consistently throughout your stack.
JSON does not natively support datetime. Use ISO 8601 strings for APIs and serialise consistently throughout your stack.
import json
from datetime import datetime, timezone
class DateTimeEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, datetime):
return obj.astimezone(timezone.utc).isoformat()
return super().default(obj)
data = {"created": datetime.now(tz=timezone.utc), "name": "Alice"}
json_str = json.dumps(data, cls=DateTimeEncoder)
# Deserialise
parsed = datetime.fromisoformat(json.loads(json_str)["created"])
Always serialise to UTC ISO 8601 — let the frontend convert to the user's local timezone.