Skip to content

Instantly share code, notes, and snippets.

@vlad-bezden
Created October 24, 2017 00:42
Show Gist options
  • Save vlad-bezden/79642f9326d776c448cf98e5191940c0 to your computer and use it in GitHub Desktop.
Save vlad-bezden/79642f9326d776c448cf98e5191940c0 to your computer and use it in GitHub Desktop.
JSON Serializer for Python objects not serializable by default (date and datetime)
import json
from datetime import date, datetime
def to_json(obj):
'''JSON serializer for objects not serializable by default'''
if isinstance(obj, (datetime, date)):
return obj.isoformat()
raise TypeError (f'Type {type(obj)} not serializable')
data = {'today': date.today(), 'time': datetime.now(), 'life': 42}
json_data = json.dumps(data, default=to_json)
print(data)
print(json_data)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment