我遇到一个问题,让我头疼了将近一天。
Python 脚本是:
# coding:utf-8
import pymongo
import datetime, time
def query_data(IP,datefrom,dateto):
conn = pymongo.MongoClient(IP)
db = conn.mymongo
startdate = time.mktime(time.strptime(datefrom,'%Y-%m-%d'))
enddate = time.mktime(time.strptime(dateto,'%Y-%m-%d'))
# all above are correct definitely.
#
# but I got no result from this line below.
cursor = db.find({'username':'test','created':{'$gte':startdate,'$lt':enddate}})
print cursor.count()
# with above code, I got 0 returned though I can see it is nonzero in database.
#
# If I use this below with single datetime, I can see result. But it is not my intention.
# cursor = db.find({'username':'test','created':datefrom})
# print cursor.count()
tempData = []
for doc in cursor:
print doc['twitter']
tempData.append(doc['twitter'])
print len(tempData)
return tempData
result = query_data('192.168.100.20','2014-4-1','2014-5-1')
问题是我上面的代码有什么问题? 或者如何使用 pymongo 脚本从 mongoDB 查询两个日期之间的数据?
最佳答案
这里有两个问题,您尝试在Database对象上调用find
,还需要使用datetime.datetime
进行查询> $gte
和 $lt
对象在 mongodb 中正常工作。
def query_data(IP,datefrom,dateto):
conn = pymongo.MongoClient(IP)
db = conn.mymongo
# time.mktime will only return a float point number
# what you really need are the datetime.datetime objects
startdate = datetime.datetime.strptime(datefrom,'%Y-%m-%d')
enddate = datetime.datetime.strptime(dateto,'%Y-%m-%d')
# you need to call find method on collection, not database object
cursor = db['your_collection'].find({'username':'test','created':{'$gte':startdate,'$lt':enddate}})
print cursor.count()
...
我还没有测试过它,但它应该可以按预期工作,希望这会有所帮助。
关于python - pymongo 按日期时间查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30098219/