vote up 13 vote down star
12

I want to send a datetime.datetime object in serialized form from Python using JSON and de-serialize in JavaScript using JSON. What is the best way to do this?

flag

3 Answers

vote up 16 vote down

For cross language projects I found out that strings containing RfC 3339 dates are the best way to go. A RfC 3339 date looks like this:

  1985-04-12T23:20:50.52Z

I think most of the format is obvious. The only somewhat unusual thing may be the "Z" at the end. It stands for GMT/UTC. You could also add a timezone offset like +02:00 for CEST (Germany in summer). I personally prefer to keep everything in UTC until it is displayed.

For displaying, comparisons and storage you can leave it in string format across all languages. If you need the date for calculations easy to convert it back to a native date object in most language.

So generate the JSON like this:

  json.dump(datetime.now().strftime('%Y-%m-%dT%H:%M:%S'))

Unfortunately Javascripts Date constructor doesn't accept RfC 3339 strings but there are many parsers available on the Internet.

link|flag
2  
This date formatting mechanism is natively supported, both by datetime: datetime.isoformat() and by simplejson, which will dump datetime objects as isoformat strings by default. No need for manual strftime hacking. – jrk Oct 21 at 5:42
@jrk - I'm not getting automatic conversion from datetime objects to the isoformat string. For me, simplejson.dumps(datetime.now()) yields TypeError: datetime.datetime(...) is not JSON serializable – kostmo 2 days ago
vote up 8 vote down

If you're certain that only Javascript will be consuming the JSON, I prefer to pass Javascript Date objects directly.

The ctime() method on datetime objects will return a string that the Javascript Date object can understand.

import datetime
date = datetime.datetime.today()
json = '{"mydate":new Date("%s")}' % date.ctime()

Javascript will happily use that as an object literal, and you've got your Date object built right in.

link|flag
2  
Technically not valid JSON, but it is a valid JavaScript object literal. (For the sake of principle I would set the Content-Type to text/javascript instead of application/json.) If the consumer will always and forever be only a JavaScript implementation, then yeah, this is pretty elegant. I would use it. – system PAUSE May 28 at 14:45
vote up 0 vote down

I can address you to eGenix Python extension, containing a lot of functions for handling date and time. Plus, i've found this article with some code to deal with Python to Javascript marshaling.

link|flag

Your Answer

Get an OpenID
or
never shown

Not the answer you're looking for? Browse other questions tagged or ask your own question.