Home >Backend Development >Python Tutorial >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>
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>
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>
By utilizing this approach, you can effortlessly handle a variety of object types during serialization.
Additional Notes
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!