Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> MongoDB

เตรียมออบเจ็กต์วันที่ Python สำหรับ Insert ลง MongoDB

คุณสามารถใช้ไลบรารี pymongo ใน Python เชื่อมต่อ MongoDB และ Insert, Update, Delete ออบเจ็กต์ ไลบรารีรองรับ datetime ของ Python ตั้งแต่ติดตั้ง ไม่ต้องทำอะไรพิเศษสำหรับการ Insert วันที่

ตัวอย่างโค้ด

from pymongo import MongoClient
from datetime import datetime

client = MongoClient()
db = client.test_database

result = db.objects.insert_one({
    "last_modified": datetime.utcnow()
})

print("Object inserted!")

ผลลัพธ์

Object inserted!

หมายเหตุ: ใช้ datetime.utcnow() คืนเวลา UTC ปัจจุบัน แทน datetime.now() ที่คืนเวลาท้องถิ่น