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?
up vote
24
down vote
favorite
17
|
|||
|
up vote
19
down vote
|
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:
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:
Unfortunately Javascripts Date constructor doesn't accept RfC 3339 strings but there are many parsers available on the Internet. |
||||||||||||||
|
up vote
10
down vote
|
You can add the 'default' parameter to json.dumps to handle this:
A more comprehensive default handler function:
Update: Added output of type as well as value. |
||||||
|
up vote
8
down vote
|
If you're certain that only Javascript will be consuming the JSON, I prefer to pass Javascript The
Javascript will happily use that as an object literal, and you've got your Date object built right in. |
||||
|
up vote
3
down vote
|
If you are using simplejson, you can subclass JSONEncoder and override the default() method to provide your own custom serializers:
Then, you can call it like this:
|
||
|
up vote
2
down vote
|
Here's a fairly complete solution for recursively encoding and decoding datetime.datetime and datetime.date objects using the standard library 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 not be decoded. I.e. this works:
And this too:
But this doesn't work as expected:
Here's the code:
|
|||
|
up vote
0
down vote
|
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. |
||
|