1

I want to set a datetime object in json body and here is what I have been doing:

#createDate is fetched from a json output of some other API  
createDate = document['createDate']

#Set in a json body
myjson = {}
myjson['date'] = dateparser.parse(createDate).astimezone(tz.tzutc())

But I get

TypeError: datetime.datetime(2014, 11, 13, 16, 23, 19, tzinfo=tzutc()) is not JSON serializable.

How to get over this?

2
  • Can you add example value for createDate? Commented May 4, 2016 at 9:09
  • There you go: 2014-11-13T11:23:19-05:00 Commented May 4, 2016 at 9:13

2 Answers 2

1
>>> import pytz
>>> from pytz import timezone
>>> utc=pytz.utc
>>> newdate=datetime.strptime(createDate, "%Y-%m-%dT%H:%M:%S-05:00")
>>> servertz = timezone("UTC")
>>> myJson={}
>>> myJson['date'] = servertz.localize(newdate).isoformat
>>> json.dumps(myJson)

Try this. The database might expecting datetime field and this will give datetime object.

Sign up to request clarification or add additional context in comments.

6 Comments

GOt datetime.datetime(2014, 11, 13, 11, 23, 19, tzinfo=<UTC>) is not JSON serializable
Just checked type(myJson) is dict and not json.
ok when I send the response to the browser I have "response = json.dumps(student)" That's where it is failing.
ok I got it now.. instead of myJson['date'] = servertz.localize(newdate) use myJson['date'] = servertz.localize(newdate).isoformat() now json.dumps(myJson) should work without error.
type(servertz.localize(newdate).isoformat()) gives me <class 'str'> which means it makes it a string instead of datetime object
|
1

The error is quite explicit, a datetime object is indeed not json serializable. You have two options. The first one, more complex, is to write your own serializer for datetime object. The second option, probably easier, is to simply convert your datetime object to a string. Like this:

createDate = document['createDate']
myjson = {}
myjson['date'] = dateparser.parse(createDate).astimezone(tz.tzutc()).isoformat()

4 Comments

Well problem is this json object goes into a databse which only accepts datetime object so converting into string is not an option.
I struggle to believe that. All databases that I know accept strings.
I mean my database column is of type DATETIME document_createdate DATETIME,
Are you sure that the database won't be able to read the datetime date which was saved as string?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.