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?

codec
  • 7,978
  • 26
  • 71
  • 127

2 Answers2

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()
DevShark
  • 8,558
  • 9
  • 32
  • 56
  • Well problem is this json object goes into a databse which only accepts datetime object so converting into string is not an option. – codec May 04 '16 at 09:14
  • 1
    I struggle to believe that. All databases that I know accept strings. – DevShark May 04 '16 at 09:15
  • I mean my database column is of type DATETIME `document_createdate DATETIME,` – codec May 04 '16 at 09:18
  • Are you sure that the database won't be able to read the datetime date which was saved as string? – Yaron May 04 '16 at 09:24
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.

  • GOt `datetime.datetime(2014, 11, 13, 11, 23, 19, tzinfo=) is not JSON serializable` – codec May 04 '16 at 09:38
  • Just checked type(myJson) is `dict` and not json. – codec May 04 '16 at 09:46
  • ok when I send the response to the browser I have "response = json.dumps(student)" That's where it is failing. – codec May 04 '16 at 09:51
  • 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. – Suresh Jaganathan May 04 '16 at 09:54
  • `type(servertz.localize(newdate).isoformat())` gives me `` which means it makes it a string instead of datetime object – codec May 04 '16 at 10:00
  • I did this for response `response = jsonify(students=students)` instead of `json.dumps`. This is working good. students is a list of students. :) Thanks a lot for your help! – codec May 04 '16 at 10:03