Skip to content

Instantly share code, notes, and snippets.

@mschulz
Created September 23, 2024 04:28
Show Gist options
  • Save mschulz/0118bf062db2c58d043de594bd299df7 to your computer and use it in GitHub Desktop.
Save mschulz/0118bf062db2c58d043de594bd299df7 to your computer and use it in GitHub Desktop.
JSON and datetime objects
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