Search code examples
mongodbdatetimepymongoisodate

TypeError: datetime.datetime() is not JSON serializable


I have a problem regarding timestamps in MongoDB.

So here's the case:

I read in the json's and add timestamp to them:

my_json['insertTime'] = datetime.datetime.now()
mongodb.collection.insert_one(my_json)

will result in the DB like that:

"insertTime" : ISODate("2017-05-24T12:39:34.844Z")

After I read it then from the DB and try to write the same document into another mongoDB table I get the following error:

TypeError: datetime.datetime(2017, 5, 24, 12, 39, 46, 671000) is not JSON serializable

I have read solutions that will convert the datetime into a string value, but I'd like it to be in the ISODate format like in the first table.

That's how the timestamp looks like after getting it from table A:

'insertTime': datetime.datetime(2017, 5, 24, 12, 39, 46, 671000)

What should I do to insert it into the second table with same format (ISODate)?

PS: the way I load data into table B is the following:

tableB.insert_one(json.loads(json.dumps(docFromTableA)))

Solution

  • There is no need to pass through a JSON representation in order to save a document to MongoDB. Just do:

    tableB.insert_one(docFromTableA)
    

    MongoDB's native data format is not JSON, it is BSON, a binary structure with many more types than JSON. PyMongo converts MongoDB documents between BSON and Python dicts automatically.