Login

Encoding datetime for JSON consumers like YUI

Author:
acdha
Posted:
December 22, 2009
Language:
Python
Version:
1.1
Score:
1 (after 1 ratings)

Passing datetimes from Python to a YUI DataTable via JSON served by django-piston turned out to be surprisingly rocky. This code actually works with YAHOO.lang.JSON.stringToDate (not YAHOO.util.DataSource.parseDate) which cannot handle time zone specifiers other than "Z" or dates without timezones.

The YUI DataSource which uses this looks something like this - note that simply setting format:"date" does not work as that uses YAHOO.util.DataSource.parseDate, which usesDate.parse to do the actual conversion, which will involve browser-specific formats and as of this writing only Chrome's native Date can reliably parse ISO 8601 dates.

myDataSource.responseSchema = {
    resultsList: '…',
    fields: [
        …
        {
            key: 'my_date_field', 
            parser: YAHOO.lang.JSON.stringToDate
        },
    ],
    …
};
1
2
3
4
# Unlike datetime.isoformat(), this works in UTC and has the trailing Z which is
# required by JSON parsers such as YAHOO.lang.JSON.stringToDate:

time.strftime('%Y-%m-%dT%H:%M:%SZ', date.utctimetuple())

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 10 months, 2 weeks ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 3 weeks ago
  3. Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
  5. Help text hyperlinks by sa2812 1 year, 6 months ago

Comments

Please login first before commenting.