Created
September 23, 2024 04:28
-
-
Save mschulz/0118bf062db2c58d043de594bd299df7 to your computer and use it in GitHub Desktop.
JSON and datetime objects
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import json | |
from datetime import datetime | |
def datetime_handler(x): | |
if isinstance(x, datetime): | |
return x.isoformat() | |
raise TypeError("Unknown type") | |
data = {'name': 'Alice', 'date': datetime.now()} | |
json_string = json.dumps(data, default=datetime_handler) | |
print(json_string) # {"name": "Alice", "date": "2024-08-23T14:16:47.139272"} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment