Apply Now Apply Now Apply Now
header_logo
Post thumbnail
PYTHON

Handling JSON Datetime Between Python and JavaScript: A Complete 2026 Guide

By Jebasta

Have you ever tried sending a date from Python to JavaScript or vice versa, only to realize the formats do not match? You are not alone. Handling JSON datetime between Python and JavaScript can be tricky because each language handles date and time differently. The datetime object in Python is not natively JSON serializable, while JavaScript uses its own Date format that can behave inconsistently across environments.

In this blog, we will break it down step by step, helping you understand how to convert Python datetime to JSON, parse JSON date format in JavaScript, manage timezones correctly, and handle common errors that come up when handling JSON datetime between Python and JavaScript in production applications. By the end, you will have a complete, working reference for handling JSON datetime between Python and JavaScript in any full-stack project.

Quick Answer:

Handling JSON datetime between Python and JavaScript requires converting Python datetime objects to ISO 8601 strings using .isoformat() before serialization, and then parsing those strings in JavaScript using new Date() or Date.parse(). The ISO 8601 format (YYYY-MM-DDTHH:mm:ss.sssZ) is the universally accepted standard for handling JSON datetime between Python and JavaScript reliably across timezones and environments.

Table of contents


  1. Why Handling JSON Datetime Between Python and JavaScript Is Tricky
  2. Handling JSON Datetime Between Python and JavaScript
    • Python and JSON Datetime
    • Using a Custom JSON Encoder for Datetime
    • Parsing JSON Datetime Back in Python
    • JavaScript and JSON Datetime Parsing
    • Converting JavaScript Date Back to ISO String for Python
  3. Handling Timezones When Working with JSON Datetime Between Python and JavaScript
    • Making Python Datetime Timezone-Aware (UTC)
    • JavaScript Timezone Gotchas
    • Differences Between Python and JavaScript Datetime Handling
  4. Common Errors and How to Fix Them
  5. Real-World Example: Full-Stack API Flow
    • 💡 Did You Know?
  6. Conclusion
  7. FAQs
    • Why does Python throw an error when trying to serialize datetime to JSON? 
    • How do I ensure the datetime is in UTC when converting from Python? 
    • How can I format a JavaScript Date object back into JSON format? 
    • What is the best format to store datetime in JSON?

Why Handling JSON Datetime Between Python and JavaScript Is Tricky

Before diving into the code, it helps to understand why handling JSON datetime between Python and JavaScript is a common source of bugs in full-stack applications.

Python’s datetime module stores dates as objects with rich metadata: year, month, day, hour, minute, second, microsecond, and optional timezone info. Python’s json module has no idea what to do with these objects by default and throws a TypeError if you try to serialize them directly.

JavaScript’s Date object stores dates as milliseconds since the Unix epoch (January 1, 1970). When parsing strings, JavaScript is relatively flexible but can behave inconsistently depending on the format and the browser or Node.js version.

The bridge between the two is ISO 8601, an international standard format that both Python and JavaScript understand and produce reliably. Mastering this format is the core of handling JSON datetime between Python and JavaScript correctly.

ProblemPython BehaviorJavaScript Behavior
Native datetime in JSONThrows TypeErrorDate object not JSON serializable either
Preferred string formatISO 8601 via .isoformat()ISO 8601 via .toISOString()
Timezone handlingNaive (no timezone) by defaultLocal timezone by default
UTC outputRequires explicit timezone.utcRequires .toISOString() which always outputs UTC
MicrosecondsSupported (6 decimal places)Not supported (3 decimal places max)

Think about this: handling JSON datetime between Python and JavaScript is essentially a translation problem. Both languages speak their own dialect of time, and ISO 8601 is the common language they share.

Handling JSON Datetime Between Python and JavaScript

Python and JSON Datetime

In Python, working with dates and times is done using the datetime module. However, when serializing datetime objects to JSON, we need to convert them into a format that JSON understands, such as ISO 8601 format.

Converting Python Datetime to JSON

Python’s json module doesn’t support datetime objects directly. If you try to serialize a datetime object, you’ll get an error:

import json

from datetime import datetime

data = {“timestamp”: datetime.now()}

json.dumps(data)  # Raises TypeError

To fix this, we need to convert the datetime object to a string in ISO format:

data = {“timestamp”: datetime.now().isoformat()}

json_data = json.dumps(data)

print(json_data)

This outputs something like:

{“timestamp”: “2025-03-01T12:34:56.789123”}

This format (ISO 8601) is widely accepted and works well with JavaScript.

Using a Custom JSON Encoder for Datetime

For larger applications where you want to serialize datetime objects automatically without manually calling .isoformat() everywhere, you can write a custom JSON encoder. This is the production-ready approach for handling JSON datetime between Python and JavaScript at scale, especially in Flask or Django APIs that return many datetime fields:

import json from datetime import datetime

class DateTimeEncoder(json.JSONEncoder):     def default(self, obj):         if isinstance(obj, datetime):             return obj.isoformat()         return super().default(obj)

data = {“timestamp”: datetime.now(), “event”: “user_login”} json_data = json.dumps(data, cls=DateTimeEncoder) print(json_data)

Output:

{“timestamp”: “2026-03-01T12:34:56.789123”, “event”: “user_login”}

This approach is especially useful in Flask or Django backends where you need consistent datetime serialization across multiple API endpoints.

MDN

Parsing JSON Datetime Back in Python

When receiving a JSON datetime string from JavaScript or any other source, Python needs to parse it back into a datetime object:

from datetime import datetime

timestamp_str = “2026-03-01T12:34:56.789123” dt = datetime.fromisoformat(timestamp_str) print(dt) # 2026-03-01 12:34:56.789123

For ISO 8601 strings with a UTC ‘Z’ suffix (sent from JavaScript’s .toISOString()):

timestamp_str = “2026-03-01T12:34:56.000Z” dt = datetime.fromisoformat(timestamp_str.replace(“Z”, “+00:00”)) print(dt) # 2026-03-01 12:34:56+00:00

Note: Python 3.11 and above can parse the ‘Z’ suffix directly without the replace workaround.

JavaScript and JSON Datetime Parsing

JavaScript’s Date object makes it easy to handle dates and times, but parsing JSON datetime strings requires special attention.

JavaScript Datetime Parse

Let’s assume we received the JSON datetime from Python:

{“timestamp”: “2025-03-01T12:34:56.789123”}

We can parse this in JavaScript using:

const jsonData = ‘{“timestamp”: “2025-03-01T12:34:56.789123”}’;

const parsedData = JSON.parse(jsonData);

const dateObject = new Date(parsedData.timestamp);

console.log(dateObject);  // Sat Mar 01 2025 12:34:56 GMT+0000 (UTC)

Converting JavaScript Date Back to ISO String for Python

When sending a datetime from JavaScript to a Python backend, always use .toISOString() to ensure you produce a format Python can reliably parse:

const now = new Date(); const isoString = now.toISOString(); console.log(isoString); // “2026-03-01T12:34:56.789Z”

// Send to Python backend: fetch(‘/api/data’, {     method: ‘POST’,     headers: { ‘Content-Type’: ‘application/json’ },     body: JSON.stringify({ timestamp: isoString }) });

On the Python backend:

from datetime import datetime import json

body = ‘{“timestamp”: “2026-03-01T12:34:56.789Z”}’ data = json.loads(body) dt = datetime.fromisoformat(data[“timestamp”].replace(“Z”, “+00:00”)) print(dt) # 2026-03-01 12:34:56+00:00

Handling Timezones When Working with JSON Datetime Between Python and JavaScript

Timezone handling is the most error-prone part of handling JSON datetime between Python and JavaScript. The golden rule is: always store and transmit datetimes in UTC, and convert to local time only for display. This single rule eliminates 90% of timezone bugs in handling JSON datetime between Python and JavaScript.

Making Python Datetime Timezone-Aware (UTC)

A naive datetime in Python has no timezone info. Always use timezone-aware datetimes for API communication:

from datetime import datetime, timezone

# Naive datetime (avoid for APIs) naive_dt = datetime.now() print(naive_dt.isoformat()) # “2026-03-01T12:34:56.789123” — no timezone info

# Timezone-aware datetime (correct for handling JSON datetime between Python and JavaScript) aware_dt = datetime.now(timezone.utc) print(aware_dt.isoformat()) # “2026-03-01T12:34:56.789123+00:00” — explicit UTC

json.dumps({“timestamp”: aware_dt.isoformat()})

JavaScript Timezone Gotchas

JavaScript’s new Date() without an explicit timezone always uses the local system timezone. This is a common source of bugs when handling JSON datetime between Python and JavaScript in multi-timezone applications:

// Problem: Parses in LOCAL timezone const local = new Date(“2026-03-01T12:34:56”);

// Safe: Always use UTC-explicit strings from Python const utc = new Date(“2026-03-01T12:34:56+00:00”); const utcZ = new Date(“2026-03-01T12:34:56.000Z”);

// Display in user’s local timezone (correct approach) console.log(utcZ.toLocaleString(“en-IN”, { timeZone: “Asia/Kolkata” })); // Shows time in IST for Indian users

Differences Between Python and JavaScript Datetime Handling

FeaturePython (datetime)JavaScript (Date)
Default FormatNot JSON serializableISO 8601 (String via .toISOString())
Conversion Needed.isoformat()new Date() parsing
Timezone HandlingNaive by default (no timezone)Local timezone by default
UTC Outputdatetime.now(timezone.utc)new Date().toISOString() always UTC
MicrosecondsSupported (6 decimal places)Not supported (3 decimal places)
Parsing backdatetime.fromisoformat()new Date(string)
JSON serializationRequires custom encoderJSON.stringify() handles Date as string
Best format for exchangeISO 8601 with +00:00 offsetISO 8601 with Z suffix

Common Errors and How to Fix Them

ErrorCauseFix
TypeError: Object of type datetime is not JSON serializableDirect json.dumps on datetime objectConvert with .isoformat() or use custom encoder
Invalid Date in JavaScriptPython sent naive datetime without timezoneUse datetime.now(timezone.utc).isoformat()
Time is off by hoursTimezone mismatch between systemsAlways use UTC for storage and transmission
Python fromisoformat fails on “Z” suffixPython < 3.11 does not parse “Z”Replace “Z” with “+00:00” before parsing
Microseconds causing JavaScript parse errorPython sends 6 decimal placesTruncate to 3 using .strftime or slice the string

This errors table covers the five bugs developers encounter most often when handling JSON datetime between Python and JavaScript in real projects.

Real-World Example: Full-Stack API Flow

Here is a complete end-to-end example showing handling JSON datetime between Python and JavaScript in a Flask and JavaScript application. This pattern covers the full round trip and is the recommended approach for handling JSON datetime between Python and JavaScript in any REST API project:

Python Flask Backend:

from flask import Flask, jsonify, request from datetime import datetime, timezone

app = Flask(name)

@app.route(‘/api/event’, methods=[‘GET’]) def get_event():     event = {         “name”: “User Login”,         “timestamp”: datetime.now(timezone.utc).isoformat()     }     return jsonify(event)

@app.route(‘/api/event’, methods=[‘POST’]) def post_event():     data = request.get_json()     ts_str = data.get(“timestamp”, “”)     dt = datetime.fromisoformat(ts_str.replace(“Z”, “+00:00”))     return jsonify({“received_at”: dt.isoformat(), “status”: “ok”})

JavaScript Frontend:

// GET: Receive and display datetime from Python fetch(‘/api/event’)     .then(res => res.json())     .then(data => {         const dt = new Date(data.timestamp);         console.log(“Event time (local):”, dt.toLocaleString());     });

// POST: Send datetime from JavaScript to Python const payload = { timestamp: new Date().toISOString() }; fetch(‘/api/event’, {     method: ‘POST’,     headers: { ‘Content-Type’: ‘application/json’ },     body: JSON.stringify(payload) });

Want to explore JavaScript in-depth? Do register for HCL GUVI’s JavaScript self-paced course where you will learn concepts such as the working of JavaScript and its many benefits, Variables, Objects, Operators, and Functions, as well as advanced topics like Closures, Hoisting, and Classes to name a few. You will also learn concepts pertaining to the latest update of ES6.

💡 Did You Know?

  • The ISO 8601 standard that underpins handling JSON datetime between Python and JavaScript was first published by the International Organization for Standardization in 1988 and has been the global standard for date and time representation in software ever since. Every developer working on full-stack projects should know this standard cold before attempting handling JSON datetime between Python and JavaScript in production.
  • Python 3.11 (released in 2022 and now the dominant production version in 2026) finally added native support for parsing ISO 8601 strings with the “Z” suffix, eliminating the most common workaround required when handling JSON datetime between Python and JavaScript.

Conclusion

Handling datetime in JSON between Python and JavaScript is all about using ISO 8601 format. Python requires explicit conversion using .isoformat(), while JavaScript can directly parse and work with ISO format dates. Understanding these differences ensures smooth data exchange between backend and frontend applications.

FAQs

1. Why does Python throw an error when trying to serialize datetime to JSON? 

Python’s json module doesn’t support datetime objects natively. You need to convert them to a string using .isoformat() before serialization.

2. How do I ensure the datetime is in UTC when converting from Python? 

Use .isoformat() with timezone-aware datetime objects:
from datetime import datetime, timezone
dt = datetime.now(timezone.utc)
json.dumps({“timestamp”: dt.isoformat()})

3. How can I format a JavaScript Date object back into JSON format? 

Use .toISOString():
const now = new Date();
console.log(now.toISOString());
This ensures compatibility with Python and other systems.

MDN

4. What is the best format to store datetime in JSON?

ISO 8601 (YYYY-MM-DDTHH:mm:ss.sssZ) is the best format as it is universally accepted and easy to parse in both Python and JavaScript.

Success Stories

Did you enjoy this article?

Schedule 1:1 free counselling

Similar Articles

Loading...
Get in Touch
Chat on Whatsapp
Request Callback
Share logo Copy link
Table of contents Table of contents
Table of contents Articles
Close button

  1. Why Handling JSON Datetime Between Python and JavaScript Is Tricky
  2. Handling JSON Datetime Between Python and JavaScript
    • Python and JSON Datetime
    • Using a Custom JSON Encoder for Datetime
    • Parsing JSON Datetime Back in Python
    • JavaScript and JSON Datetime Parsing
    • Converting JavaScript Date Back to ISO String for Python
  3. Handling Timezones When Working with JSON Datetime Between Python and JavaScript
    • Making Python Datetime Timezone-Aware (UTC)
    • JavaScript Timezone Gotchas
    • Differences Between Python and JavaScript Datetime Handling
  4. Common Errors and How to Fix Them
  5. Real-World Example: Full-Stack API Flow
    • 💡 Did You Know?
  6. Conclusion
  7. FAQs
    • Why does Python throw an error when trying to serialize datetime to JSON? 
    • How do I ensure the datetime is in UTC when converting from Python? 
    • How can I format a JavaScript Date object back into JSON format? 
    • What is the best format to store datetime in JSON?