JSON
datetime
Python
JavaScript
data conversion

JSON datetime between Python and JavaScript

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Introduction

JSON has no native datetime type, so Python and JavaScript systems must agree on a string representation. Most cross-platform bugs come from timezone ambiguity, inconsistent precision, or inconsistent parsing behavior. A stable contract based on ISO 8601 UTC strings avoids most interoperability issues.

Core Sections

Use a Single Wire Format

Recommended wire format:

  • ISO 8601
  • UTC timezone marker Z
  • explicit seconds and optional milliseconds

Example value:

text
2026-03-05T18:30:00Z

Do not send locale-specific date strings in APIs.

Python: Serialize Datetime to JSON Safely

Python datetime objects are not JSON serializable by default. Convert explicitly:

python
1import json
2from datetime import datetime, timezone
3
4payload = {
5    "event": "job_finished",
6    "created_at": datetime.now(timezone.utc).isoformat().replace("+00:00", "Z")
7}
8
9text = json.dumps(payload)
10print(text)

Using timezone-aware datetimes prevents accidental local-time serialization.

Python: Parse Incoming JSON Datetime

For strict UTC parsing:

python
1from datetime import datetime, timezone
2
3value = "2026-03-05T18:30:00Z"
4dt = datetime.fromisoformat(value.replace("Z", "+00:00"))
5print(dt, dt.tzinfo)

Normalize to UTC in backend boundaries, then convert to local display only in UI layers.

JavaScript: Parse and Serialize Predictably

JavaScript Date can parse ISO 8601 UTC strings directly:

javascript
const raw = "2026-03-05T18:30:00Z";
const d = new Date(raw);
console.log(d.toISOString());

When serializing current time in API requests:

javascript
1const payload = {
2  event: "client_ping",
3  sent_at: new Date().toISOString()
4};

toISOString always returns UTC with Z suffix.

End-to-End Example

Python server response:

python
1import json
2from datetime import datetime, timezone
3
4response = json.dumps({
5    "id": 123,
6    "created_at": datetime(2026, 3, 5, 18, 30, tzinfo=timezone.utc)
7        .isoformat()
8        .replace("+00:00", "Z")
9})
10print(response)

JavaScript client parsing:

javascript
1const response = '{"id": 123, "created_at": "2026-03-05T18:30:00Z"}';
2const obj = JSON.parse(response);
3const createdAt = new Date(obj.created_at);
4console.log(createdAt.toISOString());

Both sides preserve the same instant in time.

Epoch Timestamps as an Alternative

If you prefer numeric transport, use Unix epoch milliseconds:

Python:

python
1from datetime import datetime, timezone
2
3ms = int(datetime.now(timezone.utc).timestamp() * 1000)
4print(ms)

JavaScript:

javascript
const ms = Date.now();
const d = new Date(ms);
console.log(d.toISOString());

Epoch values avoid parsing quirks but are less human-readable in logs.

Avoid Naive Datetimes in Python

Naive datetime objects lack timezone info and often cause accidental local-time assumptions. Always use timezone-aware objects at serialization boundaries.

Good pattern:

python
from datetime import datetime, timezone

dt = datetime.now(timezone.utc)

This prevents subtle offset bugs during daylight-saving changes.

API Contract Recommendations

For reliable cross-language behavior:

  1. define datetime field format in API spec
  2. require UTC in wire payloads
  3. include examples in docs
  4. validate at request boundaries

Explicit contracts prevent teams from inventing incompatible local conventions.

Testing Timezone Behavior

Add tests for:

  • UTC round trip
  • non-UTC input normalization
  • daylight-saving transition dates
  • milliseconds precision retention

Time bugs are expensive in production. Tests are cheaper.

Contract Example for API Documentation

Document datetime fields explicitly in your API specification so consumers do not guess format:

text
created_at: ISO 8601 UTC string, example 2026-03-05T18:30:00Z

Small contract details like this prevent long debugging sessions across backend and frontend teams.

Common Pitfalls

  • Sending local time strings without timezone marker.
  • Serializing naive Python datetimes and assuming UTC.
  • Using browser-local formatting as API payload format.
  • Parsing mixed datetime formats in one endpoint.
  • Ignoring precision differences between systems when comparing timestamps.

Summary

  • JSON needs explicit datetime encoding strategy between Python and JavaScript.
  • ISO 8601 UTC strings are the safest default for API payloads.
  • Use timezone-aware datetimes in Python and toISOString in JavaScript.
  • Keep display timezone conversion in UI, not transport layer.
  • Add round-trip tests to catch timezone and precision regressions early.

Course illustration
Course illustration