How to Convert Datetime Objects Between Python and JavaScript Using JSON

DDD
Release: 2024-10-20 19:15:02
Original
564 people have browsed it

How to Convert Datetime Objects Between Python and JavaScript Using JSON

Converting Datetime Objects between Python and JavaScript using JSON

In the realm of data serialization and deserialization, the exchange of datetime objects between Python and JavaScript via JSON can pose a challenge. Let's delve into how we can tackle this issue and present the best approach to handle this conversion.

Serialization in Python

To serialize a datetime.datetime object from Python to JSON, we can employ Python's built-in json.dumps() function. However, to ensure proper handling of datetime objects, we need to provide a custom 'default' parameter. Here's a sample code snippet:

<code class="python">import datetime
import json

date_handler = lambda obj: (
    obj.isoformat()
    if isinstance(obj, (datetime.datetime, datetime.date))
    else None
)

json_string = json.dumps(datetime.datetime.now(), default=date_handler)
print(json_string)  # Output: "2010-04-20T20:08:21.634121"</code>
Copy after login

This approach ensures that datetime objects are serialized in ISO 8601 format, which is widely supported for date and time representation.

Deserialization in JavaScript

If you use a JavaScript library that handles JSON parsing, such as JSON.parse(), it will automatically deserialize the ISO 8601 string into a Date object. Here's how it would look in JavaScript:

<code class="js">const json_object = JSON.parse(json_string);
const js_date = new Date(json_object);  // Converted to JavaScript Date object</code>
Copy after login

Comprehensive Default Handler

For a more comprehensive approach, consider using a default handler function that handles a wider range of object types during serialization:

<code class="python">def handler(obj):
    if hasattr(obj, 'isoformat'):
        return obj.isoformat()
    elif isinstance(obj, ...):
        return ...
    else:
        raise TypeError, 'Object of type %s with value of %s is not JSON serializable' % (type(obj), repr(obj))</code>
Copy after login

By utilizing this approach, you can effortlessly handle a variety of object types during serialization.

Additional Notes

  • ISO 8601 is a standard for representing dates and times in a machine-readable format.
  • The output of the custom handler should match the format expected by the deserializer.
  • For more information, refer to Python's json.dumps() and JavaScript's JSON.parse() documentation.

The above is the detailed content of How to Convert Datetime Objects Between Python and JavaScript Using JSON. For more information, please follow other related articles on the PHP Chinese website!

source:php
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!