如何准备要插入MongoDB的Python日期对象?

您可以使用Python中的pymongo库连接到MongoDB数据库,并使用它在Python中插入,更新,删除等对象。该库开箱即用地支持Python日期时间对象,您无需执行任何特殊操作即可使用PyMongo在Mongo中插入日期。

示例

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("对象已插入!")

输出结果

这将给出输出-

对象已插入!

注意-始终使用datetime.datetime.utcnow()(以UTC返回当前时间),而不要使用datetime.datetime.now()(以返回当前本地时间)。