How to prepare a Python date object to be inserted into MongoDB?

PythonServer Side ProgrammingProgrammingMongoDB

You can use the pymongo library in Python to connect to a MongoDB database and use it to insert, update, delete, etc objects in Python. The library supports Python datetime objects out of the box and you dont need to do anything special to insert dates in Mongo using PyMongo.


from pymongo import MongoClient
# This will try to connect to MongoDB on the default port and host
client = MongoClient()
db = client.test_database
# Insert the given dictionary to the objects collection:
result = db.objects.insert_one({"last_modified": datetime.datetime.utcnow()})
print("Object inserted!")


This will give the output −

Object inserted!

Note − Always use datetime.datetime.utcnow(), which returns the current time in UTC, instead of, which returns the current local time.

Published on 08-Jan-2018 10:59:32