Datetime.datetime is not serializable JSON

I have a class in Python to retrieve all the columns in a table and return JSON with this data.

The problem is that at least one of these columns is a datetime, and I cannot figure out how to serialize the columns so that I can create a valid JSON.

My class is as follows:

class GetTodos(Resource): def get(self): con = cx_Oracle.connect('brunojs/ bdpf5@127.0.0.1 /orcl') cur = con.cursor() cur.execute("select * from organite_repository") r = [dict((cur.description[i][0], value) \ for i, value in enumerate(row)) for row in cur.fetchall()] cur.connection.close() return (r[0] if r else None) if None else r 

Any hints of this?

+7
python datetime
source share
2 answers

JSON does not have a datetime type by default, so Python cannot process it automatically. So you need to make datetime into a string anyway. I think the best way is to write a custom handler to help the json module.

 import datetime import json def datetime_handler(x): if isinstance(x, datetime.datetime): return x.isoformat() raise TypeError("Unknown type") json.dumps(data, default=datetime_handler) 
+19
source share

An easy way to do this is to pass data to a string. This way you can reset using json.

 >>> datetime.now() datetime.datetime(2016, 3, 8, 11, 37, 24, 123639) >>> str(datetime.now()) '2016-03-08 11:37:27.511053' 

But you can also implement a serializer to convert the data as you wish.

+3
source share

All Articles