本文介绍了pymongo:未定义名称"ISODate"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
当我尝试使用pymongo在mongodb中选择数据时,我遇到了问题,这是我的代码:
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 import datetime
try:
conn=pymongo.MongoClient('10.33.109.228',27017)
db=conn.mnemosyne
data_ip=db.session.aggregate({'$match':{'timestamp':{'$gte': ISODate('2016-11-11T00:00:00.000Z'),'$lte': ISODate('2016-11-11T23:59:59.000Z')}}},{'$group':{'_id':'$source_ip'}})
for f in data_ip:
print f['_id']
except pymongo.errors.ConnectionFailure, e:
print "Could not connect to MongoDB: %s" % e
当我执行它时,我会遇到这样的错误:
and when i execute it i have some error like this:
Traceback (most recent call last):
File "test.py", line 9, in <module>
data_ip=db.session.aggregate({'$match':{'timestamp':{'$gte': ISODate('2016-11-11T00:00:00.000Z'),'$lte': ISODate('2016-11-11T23:59:59.000Z')}}},{'$group':{'_id':'$source_ip'}})
NameError: name 'ISODate' is not defined
我想要这样的结果:
{ "_id" : "60.18.133.207" }
{ "_id" : "178.254.52.96" }
{ "_id" : "42.229.218.192" }
{ "_id" : "92.82.171.117" }
{ "_id" : "103.208.120.205" }
{ "_id" : "185.153.208.142" }
这是mydatabase的示例结构:
this is example structure of mydatabase:
> db.session.findOne()
{
"_id" : ObjectId("5786398d1f50070f31f27f7c"),
"protocol" : "epmapper",
"hpfeed_id" : ObjectId("5786398d1f50070f31f27f7b"),
"timestamp" : ISODate("2016-07-13T12:52:29.112Z"),
"source_ip" : "23.251.55.182",
"source_port" : 2713,
"destination_port" : 135,
"identifier" : "d3374f14-48f7-11e6-9e19-0050569163b4",
"honeypot" : "dionaea"
}
请帮助我纠正错误
推荐答案
ISODate
是Mongo shell中的一个函数,它是一个javascript环境,在Python中不可用.
ISODate
is a function in the Mongo shell, which is a javascript environment, it's not available within Python.
您可以使用 dateutil 在Python中将字符串转换为datetime对象,
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())
使用PyMongo
,如果要在MongoDB
中插入日期时间,只需执行以下操作:
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})
这篇关于pymongo:未定义名称"ISODate"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!