Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Here's a fairly complete solution for recursively encoding and decoding datetime.datetime and datetime.date objects using the standard library <code>json</code> module. This needs Python >= 2.6 since the <code>%f</code> format code in the datetime.datetime.strptime() format string is only supported in since then. For Python 2.5 support, drop the <code>%f</code> and strip the microseconds from the ISO date string before trying to convert it, but you'll loose microseconds precision, of course. For interoperability with ISO date strings from other sources, which may include a time zone name or UTC offset, you may also need to strip some parts of the date string before the conversion. For a complete parser for ISO date strings (and many other date formats) see the third-party <a href="http://labix.org/python-dateutil" rel="noreferrer">dateutil</a> module.</p> <p>Decoding only works when the ISO date strings are values in a JavaScript literal object notation or in nested structures within an object. ISO date strings, which are items of a top-level array will <em>not</em> be decoded.</p> <p>I.e. this works:</p> <pre><code>date = datetime.datetime.now() &gt;&gt;&gt; json = dumps(dict(foo='bar', innerdict=dict(date=date))) &gt;&gt;&gt; json '{"innerdict": {"date": "2010-07-15T13:16:38.365579"}, "foo": "bar"}' &gt;&gt;&gt; loads(json) {u'innerdict': {u'date': datetime.datetime(2010, 7, 15, 13, 16, 38, 365579)}, u'foo': u'bar'} </code></pre> <p>And this too:</p> <pre><code>&gt;&gt;&gt; json = dumps(['foo', 'bar', dict(date=date)]) &gt;&gt;&gt; json '["foo", "bar", {"date": "2010-07-15T13:16:38.365579"}]' &gt;&gt;&gt; loads(json) [u'foo', u'bar', {u'date': datetime.datetime(2010, 7, 15, 13, 16, 38, 365579)}] </code></pre> <p>But this doesn't work as expected:</p> <pre><code>&gt;&gt;&gt; json = dumps(['foo', 'bar', date]) &gt;&gt;&gt; json '["foo", "bar", "2010-07-15T13:16:38.365579"]' &gt;&gt;&gt; loads(json) [u'foo', u'bar', u'2010-07-15T13:16:38.365579'] </code></pre> <p>Here's the code:</p> <pre><code>__all__ = ['dumps', 'loads'] import datetime try: import json except ImportError: import simplejson as json class JSONDateTimeEncoder(json.JSONEncoder): def default(self, obj): if isinstance(obj, (datetime.date, datetime.datetime)): return obj.isoformat() else: return json.JSONEncoder.default(self, obj) def datetime_decoder(d): if isinstance(d, list): pairs = enumerate(d) elif isinstance(d, dict): pairs = d.items() result = [] for k,v in pairs: if isinstance(v, basestring): try: # The %f format code is only supported in Python &gt;= 2.6. # For Python &lt;= 2.5 strip off microseconds # v = datetime.datetime.strptime(v.rsplit('.', 1)[0], # '%Y-%m-%dT%H:%M:%S') v = datetime.datetime.strptime(v, '%Y-%m-%dT%H:%M:%S.%f') except ValueError: try: v = datetime.datetime.strptime(v, '%Y-%m-%d').date() except ValueError: pass elif isinstance(v, (dict, list)): v = datetime_decoder(v) result.append((k, v)) if isinstance(d, list): return [x[1] for x in result] elif isinstance(d, dict): return dict(result) def dumps(obj): return json.dumps(obj, cls=JSONDateTimeEncoder) def loads(obj): return json.loads(obj, object_hook=datetime_decoder) if __name__ == '__main__': mytimestamp = datetime.datetime.utcnow() mydate = datetime.date.today() data = dict( foo = 42, bar = [mytimestamp, mydate], date = mydate, timestamp = mytimestamp, struct = dict( date2 = mydate, timestamp2 = mytimestamp ) ) print repr(data) jsonstring = dumps(data) print jsonstring print repr(loads(jsonstring)) </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload