您可以使用python中的pymongo库连接到mongodb数据库并使用它在python中插入、更新、删除等对象。该库支持开箱即用的 python 日期时间对象,您无需执行任何特殊操作即可使用 pymongo 在 mongo 中插入日期。例如,
示例from pymongo import mongoclient# this will try to connect to mongodb on the default port and hostclient = 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!")
输出这将给出输出 -
object inserted!
注意 - 始终使用 datetime.datetime.utcnow(),它返回 utc 中的当前时间,而不是 datetime.datetime.now(),它返回当前本地时间。
以上就是如何在 mongodb 中插入 python 对象?的详细内容。