Home >Backend Development >Python Tutorial >How to Exchange Datetime Objects Between Python and JavaScript Using JSON?

How to Exchange Datetime Objects Between Python and JavaScript Using JSON?

Barbara Streisand
Barbara StreisandOriginal
2024-10-20 19:17:02608browse

How to Exchange Datetime Objects Between Python and JavaScript Using JSON?

JSON datetime between Python and JavaScript

Exchanging datetime objects between Python and JavaScript using JSON can be challenging due to differences in their respective date and time formats. To address this, we can implement custom JSON serialization and deserialization handlers.

In Python, you can define a serialization handler function using the default parameter in the json.dumps function. This handler will be called whenever a datetime object is encountered during serialization. The following code snippet demonstrates how to create a handler for datetime objects that converts them to the ISO 8601 format:

<code class="python">date_handler = lambda obj: (
    obj.isoformat()
    if isinstance(obj, (datetime.datetime, datetime.date))
    else None
)
json.dumps(datetime.datetime.now(), default=date_handler)</code>

This will output the datetime object as a string in the ISO 8601 format:

<code class="json">"2010-04-20T20:08:21.634121"</code>

In JavaScript, you can use a custom deserialization handler to convert the received ISO 8601 string back to a datetime object. A comprehensive deserialization handler function might look like:

<code class="javascript">function handler(obj) {
    if (typeof obj === 'string') {
        if (/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}/.test(obj)) {
            // ISO 8601 Date string
            return new Date(obj);
        }
    }

    return obj;
}</code>

By using these custom handlers, you can seamlessly exchange datetime objects between Python and JavaScript using JSON, ensuring compatibility between the two platforms.

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

Statement:
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