Computer >> 컴퓨터 >  >> 프로그램 작성 >> MongoDB

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.now() 대신 현재 시간을 UTC로 반환하는 datetime.datetime.utcnow()를 항상 사용하십시오.