Created
August 31, 2016 11:51
-
-
Save vmax/cef8000da93016c4f40544457ddd2f45 to your computer and use it in GitHub Desktop.
Class that helps to serialize Python datetime/date/timedelta class
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
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) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
nice work