Skip to content

Instantly share code, notes, and snippets.

@vmax
Created August 31, 2016 11:51
Show Gist options
  • Save vmax/cef8000da93016c4f40544457ddd2f45 to your computer and use it in GitHub Desktop.
Save vmax/cef8000da93016c4f40544457ddd2f45 to your computer and use it in GitHub Desktop.
Class that helps to serialize Python datetime/date/timedelta class
class DateTimeAwareJSONEncoder(json.JSONEncoder):
"""
A JSONEncoder subclass for handling objects of types `timedelta`, `datetime` and `date`
"""
def default(self, obj):
if isinstance(obj, datetime):
return {
'__type__': 'datetime',
'year': obj.year,
'month': obj.month,
'day': obj.day,
'hour': obj.hour,
'minute': obj.minute,
'second': obj.second,
}
elif isinstance(obj, date):
return {
'__type__': 'date',
'year': obj.year,
'month': obj.month,
'day': obj.day,
}
elif isinstance(obj, timedelta):
return {
'__type__': 'timedelta',
'days': obj.days,
'seconds': obj.seconds,
}
else:
return json.JSONEncoder.default(self, obj)
@RFV
Copy link

RFV commented Sep 1, 2016

nice work

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment