When working with JSON, you may encounter the need to transfer datetime objects between Python and JavaScript. Serializing such objects can be tricky. This article explores the best practices for handling datetime objects in JSON communication.
To serialize a datetime.datetime object in Python, we can use the json.dumps function with the default parameter. This parameter allows us to specify a custom handler to convert the datetime object into a JSON-serializable 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) # Output: '"2010-04-20T20:08:21.634121"'</code>
The isoformat() method of the datetime object returns a string representation in ISO 8601 format, which is universally recognized.
In JavaScript, you can deserialize the serialized datetime string back into a Date object using the Date.parse() function:
<code class="javascript">const dateString = '"2010-04-20T20:08:21.634121"'; const date = new Date(Date.parse(dateString)); // Output: Thu Apr 20 2010 20:08:21 GMT-0400 (Eastern Daylight Time)</code>
For more complex scenarios, you may need a more comprehensive default handler function:
<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 handler can handle multiple object types and provides more informative error messages. Remember to handle both date and datetime objects as needed.
The above is the detailed content of How to Safely Serialize and Deserialize Datetime Objects in JSON between Python and JavaScript?. For more information, please follow other related articles on the PHP Chinese website!