Last active
September 16, 2022 18:10
-
-
Save ergoithz/04bae21c9a68ba71480c to your computer and use it in GitHub Desktop.
python json datetime encoder
This file contains 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
import json | |
import datetime | |
import dateutil.parser | |
class JSONEncoder(json.JSONEncoder): | |
def default(self, obj): | |
if isinstance(obj, datetime.datetime): | |
return { | |
'type': 'datetime', | |
'data': obj.isoformat() | |
} | |
if isinstance(obj, datetime.date): | |
return { | |
'type': 'date', | |
'data': obj.isoformat() | |
} | |
return super(JSONEncoder, self).default(obj) | |
class JSONDecoder(json.JSONDecoder): | |
def __init__(self, *args, **kwargs): | |
kwargs.setdefault('object_hook', self.default_object_hook) | |
super(JSONDecoder, self).__init__(*args, **kwargs) | |
def default_object_hook(self, obj): | |
if 'type' in obj and 'data' in obj: | |
if obj['type'] == 'datetime': | |
return dateutil.parser.parse(obj['data']) | |
if obj['type'] == 'date': | |
return datetime.parser.parse(obj['data']).date() | |
return obj | |
def dumps(*args, **kwargs): | |
kwargs.setdefault('cls', JSONEncoder) | |
return json.dumps(*args, **kwargs) | |
def loads(*args, **kwargs): | |
kwargs.setdefault('cls', JSONDecoder) | |
return json.loads(*args, **kwargs) | |
a = datetime.datetime.now() | |
b = dumps(a) | |
print(a) | |
print(b) | |
print(loads(b)) | |
import pytz | |
a = pytz.timezone('Europe/Madrid').localize(a) | |
b = dumps(a) | |
print(a) | |
print(b) | |
print(loads(b)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment