j2labs/dictshield — Issue #38: Datetimes are not marshalled to JSON correctly
Author: alexanderdean
Created: 2011-11-30 18:37:03+00:00
State: open

Maybe I'm just doing something wrong, but I can't seem to marshal datetimes:

#!/usr/bin/env python

from dictshield.document import Document
from dictshield.fields import DateTimeField
from datetime import datetime

class TestRepresentation(Document):
created_at = DateTimeField(required=True)

dt_now = datetime.now()

test = TestRepresentation()
test.created_at = dt_now # dt_now.isoformat() also fails, as does dt_now.ctime()

try:
test.validate()
except ShieldException, se:
print "Narcolepsy validation error: %s" % se

data = test.make_json_publicsafe(test)

Throws error:

File "/usr/lib/python2.7/dist-packages/simplejson/encoder.py", line 192, in default
raise TypeError(repr(o) + " is not JSON serializable")
TypeError: datetime.datetime(2011, 11, 30, 18, 31, 45, 842086) is not JSON serializable

Am I being crazy? By the way, there's quite a good Stack Overflow post about marshalling Python dates to JSON [here](http://stackoverflow.com/questions/455580/json-datetime-between-python-and-javascript).