ckdanny
3/1/2020 - 6:03 AM

Serialize the datetime object for mongoDB

Serialize the datetime object for mongoDB

Since json cannot serialize the datetime object, if you need to json.dumps and then write it into mongo, you need to use pymongo utility which help to serialize the datetime object

Given data like this

import datetime
import json
sample = {}
sample['title'] = "String"
sample['somedate'] = datetime.datetime.now()

json.dumps(sample)

> TypeError: datetime.datetime(2012, 8, 8, 21, 46, 24, 862000) is not JSON serializable

Solution 1:

# Convert to String Object in mongo
json.dumps(sample, indent=4, sort_keys=True, default=str)

Solution 2:

# Remain Datetime object in mongo
from bson import json_util
json.dumps(sample, default=json_util.default)

Soltion 3:

from bson import json_util
json_util.dumps(sample)

[How to overcome “datetime.datetime not JSON serializable”?]