"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Exchange Datetime Objects Between Python and JavaScript Using JSON?

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

Published on 2024-11-09
Browse:457

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:

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

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

"2010-04-20T20:08:21.634121"

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:

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;
}

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

Release Statement This article is reprinted at: 1729422917 If there is any infringement, please contact [email protected] to delete it
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3