SyntaxStudy
Sign Up
Python Intermediate 4 min read

Serialising Datetimes

Datetime Serialisation

JSON does not natively support datetime. Use ISO 8601 strings for APIs and serialise consistently throughout your stack.

Example
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"])
Pro Tip

Always serialise to UTC ISO 8601 — let the frontend convert to the user's local timezone.