Handle JSON Date Strings in Python with datetime
Learn how to convert JSON ISO 8601 date strings into Python datetime objects. Covers parsing, timezone handling, and integration with dataclasses and Pydantic.
Detailed Explanation
JSON Dates to Python datetime
JSON has no native date type. Dates are transmitted as strings, typically in ISO 8601 format. Python's datetime module provides proper date/time handling.
Example JSON
{
"id": 42,
"title": "Deploy v2.0",
"created_at": "2024-06-15T09:30:00Z",
"updated_at": "2024-06-15T14:22:33+09:00",
"due_date": "2024-07-01"
}
Generated Python (Dataclass)
from dataclasses import dataclass
from datetime import datetime, date
@dataclass
class Task:
id: int
title: str
created_at: datetime
updated_at: datetime
due_date: date
Parsing ISO 8601 Strings
from datetime import datetime, date
# Full datetime with timezone
dt = datetime.fromisoformat("2024-06-15T09:30:00Z")
# Python 3.11+: handles "Z" suffix
# Python < 3.11: replace "Z" with "+00:00"
# Date only
d = date.fromisoformat("2024-07-01")
Deserialization with Post-Processing
json.loads() returns strings, not datetime objects. You need a conversion step:
import json
data = json.loads(raw_json)
task = Task(
id=data["id"],
title=data["title"],
created_at=datetime.fromisoformat(data["created_at"]),
updated_at=datetime.fromisoformat(data["updated_at"]),
due_date=date.fromisoformat(data["due_date"]),
)
With Pydantic (Automatic)
Pydantic handles datetime parsing automatically:
from pydantic import BaseModel
from datetime import datetime, date
class Task(BaseModel):
id: int
title: str
created_at: datetime
updated_at: datetime
due_date: date
task = Task.model_validate_json(raw_json)
# created_at is already a datetime object!
Timezone Awareness
Always work with timezone-aware datetimes:
from datetime import timezone
utc_now = datetime.now(timezone.utc)
Nullable Timestamps
For fields that may be null (e.g., deleted_at):
from typing import Optional
from datetime import datetime
deleted_at: Optional[datetime] = None
Use Case
You are building a task management API client that needs to parse ISO 8601 timestamps, calculate durations, compare deadlines, and display dates in local timezones.
Try It — JSON to Python Converter
Related Topics
Handle Optional and Nullable JSON Fields in Python
Type Annotations
Convert Simple JSON to a Python Dataclass
Dataclasses
Convert JSON to a Pydantic BaseModel in Python
Pydantic & TypedDict
Convert REST API Response JSON to Python Classes
Advanced Patterns
Create Custom JSON Encoders for Python Dataclasses
Serialization