Skip to content

Instantly share code, notes, and snippets.

@ckdanny
Created March 1, 2020 06:03
Show Gist options
  • Save ckdanny/b96a300aaa9c132e7d7e6141cc9a098c to your computer and use it in GitHub Desktop.
Save ckdanny/b96a300aaa9c132e7d7e6141cc9a098c to your computer and use it in GitHub Desktop.
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”?]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment