Home  >  Article  >  Web Front-end  >  How to Handle Datetime Objects in JSON Exchange Between Python and JavaScript

How to Handle Datetime Objects in JSON Exchange Between Python and JavaScript

Susan Sarandon
Susan SarandonOriginal
2024-10-19 17:30:30487browse

How to Handle Datetime Objects in JSON Exchange Between Python and JavaScript

Handling Datetime Objects in JSON Exchange Between Python and JavaScript

When exchanging datetime objects between Python and JavaScript using JSON, there exists a challenge due to the different ways the two languages represent dates and times. This article presents the best practice for this task.

Python-to-JavaScript Conversion

To serialize a datetime.datetime object in Python for JSON transmission, use the 'default' parameter of the json.dumps function with a custom date handler function:

<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 function returns the ISO 8601 format of the datetime object, which is a widely accepted standard for date and time representation.

JavaScript-to-Python Conversion

In JavaScript, you can deserialize the received JSON string with a custom date reviver function. This function will parse the ISO 8601 string and reconstruct the datetime object:

<code class="javascript">let date_reviver = date => new Date(date);
JSON.parse(json_string, date_reviver);</code>

Comprehensive Date Handler

For a more comprehensive approach, you can create a custom date handler function that covers multiple data types:

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

This function ensures that different types of objects are handled appropriately during serialization.

Additional Notes

  • The ISO 8601 format used for datetime objects is ISO 8601.
  • This approach can also handle date objects (datetime.date) in Python.

The above is the detailed content of How to Handle Datetime Objects in JSON Exchange Between Python and JavaScript. 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