如何準備一個已插入 MongoDB 的 Python 日期物件?
你可以使用 Python 中的 pymongo 庫連線到 MongoDB 資料庫並使用它來插入、更新、刪除等 Python 中的物件。該庫支援 Python datetime 物件,而無需執行任何特殊操作即可使用 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("Object inserted!")
輸出
這將會得到輸出 -
Object inserted!
注意 - 始終使用 datetime.datetime.utcnow(),它會返回 UTC中的當前時間,而非 datetime.datetime.now(),它會返回當前的本地時間。
廣告