如何準備一個要插入到 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(),後者返回當前本地時間。

更新日期: 12-06-2020

1 千次瀏覽

開啟你的 職業生涯

透過完成此課程獲得認證

開始
廣告