Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
A JSON decoder/encoder implementation for parsing dates as datetime objects in Python
#!/usr/bin/env python
# An example of decoding/encoding datetime values in JSON data in Python.
# Code adapted from: http://broadcast.oreilly.com/2009/05/pymotw-json.html
from datetime import datetime
import json
from json import JSONDecoder
from json import JSONEncoder
obj = {'name':'foo', 'type': 'bar','date':datetime.now()}
class DateTimeDecoder(json.JSONDecoder):
def __init__(self, *args, **kargs):
JSONDecoder.__init__(self, object_hook=self.dict_to_object,
*args, **kargs)
def dict_to_object(self, d):
if '__type__' not in d:
return d
type = d.pop('__type__')
try:
dateobj = datetime(**d)
return dateobj
except:
d['__type__'] = type
return d
class DateTimeEncoder(JSONEncoder):
""" Instead of letting the default encoder convert datetime to string,
convert datetime objects into a dict, which can be decoded by the
DateTimeDecoder
"""
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,
'microsecond' : obj.microsecond,
}
else:
return JSONEncoder.default(self, obj)
j = json.loads(json.dumps(obj,cls=DateTimeEncoder), cls=DateTimeDecoder)
print j['date']
print type(j['date'])
@benjaminmgross

This comment has been minimized.

Copy link

@benjaminmgross benjaminmgross commented Jan 19, 2015

Thanks for this gist @abhinav-upadhyay, this is the best quick-summary of creating subclasses of JSONEncoders and JSONDecoders I've found yet!

@i1caro

This comment has been minimized.

Copy link

@i1caro i1caro commented Jun 1, 2016

Thanks. A beautiful implementation.

@s-c-p

This comment has been minimized.

Copy link

@s-c-p s-c-p commented Aug 14, 2017

Hey genius, mind commenting all that code?

@spattanaik75

This comment has been minimized.

Copy link

@spattanaik75 spattanaik75 commented Feb 8, 2018

Thank you :) I finally got my object to successfully work with a datetime type :)

@teszeri

This comment has been minimized.

Copy link

@teszeri teszeri commented Feb 16, 2018

Thanks! Nice solution!

@Codeberg-AsGithubAlternative-buhtz

This comment has been minimized.

Copy link

@Codeberg-AsGithubAlternative-buhtz Codeberg-AsGithubAlternative-buhtz commented Apr 2, 2018

Can you give licence informations about this code please. I would like to use (and modify a bit) your code in my GPL application (not yet released).

@Codeberg-AsGithubAlternative-buhtz

This comment has been minimized.

Copy link

@Codeberg-AsGithubAlternative-buhtz Codeberg-AsGithubAlternative-buhtz commented Apr 2, 2018

The link http://broadcast.oreilly.com/2009/05/pymotw-json.html is not working anymore. Can you update it?
Could it be this one? https://doughellmann.com/blog/2009/05/24/pymotw-json/

@u-phoria

This comment has been minimized.

Copy link

@u-phoria u-phoria commented Nov 22, 2018

See https://www.techatbloomberg.com/blog/work-dates-time-python/ for slight variation that preserves timezones.

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