How to Preserve Datetime Continuity Between Python and JavaScript via JSON?

Linda Hamilton
Release: 2024-10-20 19:13:30
Original
558 people have browsed it

How to Preserve Datetime Continuity Between Python and JavaScript via JSON?

PreservingDatetime Continuity Between Python and JavaScript via JSON

Before venturing into the solution, let's first understand the problem. We have a datetime.datetime object in Python that needs to be serialized and sent to JavaScript through JSON. Upon arrival, JavaScript must be able to deserialize it back into a datetime object without any distortions.

To address this conundrum, JSON's versatile 'default' parameter in json.dumps provides a solution. This parameter enables us to define a custom serialization handler for ourdatetime objects.

The following handler neatly handles the serialization process:

<code class="python">date_handler = lambda obj: (
    obj.isoformat()
    if isinstance(obj, (datetime.datetime, datetime.date))
    else None
)</code>
Copy after login

When applied, this handler converts datetime objects into ISO 8601 format during serialization:

<code class="python">json.dumps(datetime.datetime.now(), default=date_handler)
'"2010-04-20T20:08:21.634121"'</code>
Copy after login

For more complex scenarios, a comprehensive handler is recommended:

<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

This handler also generates an improved error message with the object's type and value for better debugging. The inclusion of a date type ensures that dates are also handled gracefully.

The above is the detailed content of How to Preserve Datetime Continuity Between Python and JavaScript via 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
Latest Articles by Author
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!