pymongo: name 'ISODate' is not defined

前端 未结 2 1965
孤城傲影
孤城傲影 2020-12-21 18:37

I have problem when i try to select data in mongodb with pymongo, this is my code :

import pymongo
from pymongo import MongoClient
import sys
from datetime i         


        
2条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-21 19:23

    ISODate is a function in the Mongo shell, which is a javascript environment, it's not available within Python.

    You can use dateutil for converting a string to datetime object in Python,

    import dateutil.parser
    dateStr = "2016-11-11T00:00:00.000Z"
    dateutil.parser.parse(dateStr)  # returns a datetime.datetime(2016, 11, 11, 00, 0, tzinfo=tzutc())
    

    Using PyMongo, if you want to insert datetime in MongoDB you can simply do the following:

    import pymongo
    import dateutil
    dateStr = '2016-11-11T00:00:00.000Z'
    myDatetime = dateutil.parser.parse(dateStr)
    client = pymongo.MongoClient()
    client.db.collection.insert({'date': myDatetime})
    

提交回复
热议问题