Created
October 19, 2010 11:53
-
-
Save lepture/634072 to your computer and use it in GitHub Desktop.
datetime_json
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
#!/usr/bin/env python | |
# -*- coding: utf-8 -*- | |
import datetime | |
from django.utils import simplejson | |
#import simplejson | |
class DateTimeJSONEncoder(simplejson.JSONEncoder): | |
""" | |
copy from django.core.serializers.json | |
""" | |
DATE_FORMAT = "%Y-%m-%d" | |
TIME_FORMAT = "%H:%M:%S" | |
def default(self, o): | |
if isinstance(o, datetime.datetime): | |
return o.strftime("%s %s" % (self.DATE_FORMAT, self.TIME_FORMAT)) | |
elif isinstance(o, datetime.date): | |
return o.strftime(self.DATE_FORMAT) | |
elif isinstance(o, datetime.time): | |
return o.strftime(self.TIME_FORMAT) | |
else: | |
return super(DateTimeJSONEncoder, self).default(o) | |
def dumps(o): | |
return simplejson.dumps(o, ensure_ascii=False,cls=DateTimeJSONEncoder) | |
def dump(obj, fp, skipkeys=False, ensure_ascii=False, check_circular=True, | |
allow_nan=True, cls=DateTimeJSONEncoder, indent=None, | |
separators=None, encoding='utf-8', default=None, **kw): | |
return simplejson.dump( | |
obj, fp, skipkeys, ensure_ascii, check_circular, | |
allow_nan, cls, indent, separators, encoding, | |
default) | |
def loads(s): | |
return simplejson.loads(s) | |
def load(fp, encoding=None, cls=None, object_hook=None, parse_float=None, | |
parse_int=None, parse_constant=None, **kw): | |
return simplejson.load( | |
fp, encoding, cls, object_hook, parse_float, | |
parse_int, parse_constant) | |
if '__main__' == __name__: | |
o = [1, 0, None, True, False, 'str', u'unicode', | |
{'dict':1,'dict2':2, u'3':3}, | |
datetime.datetime.now(), | |
] | |
data = dumps(o) | |
print data |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment