Python 按日期时间的pymongo查询
我有一个问题几乎让我头痛了一天 python脚本包括:Python 按日期时间的pymongo查询,python,python-2.7,pymongo,Python,Python 2.7,Pymongo,我有一个问题几乎让我头痛了一天 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
# 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查询数据?这里有两个问题,您试图调用
查找数据库对象上的,还需要使用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()
...
我还没有测试过它,但它应该能按预期工作,希望这能有所帮助。在mongodb中,日期时间应该是ISODate
object,尝试比较newdate(…)
instead我尝试了两种方法:db.find({'username':'test','created':{'gte':newdatefrom),'lt':newdate(dateto)})和db.find({'username':'test','created':{'new Date(datefrom)',$lt':'new Date(dateto)}}这两种方式都没有给我任何结果。我使用了错误的格式吗?你试过只使用datetime.datetime
?@Anzel是的,我使用了,但使用了这种格式datetime.datetime(2014,3,1)对于每个。我错了吗?另外,你确定你的startdate
和enddate
设置正确了吗,即混淆了吗?关于你的数据的更多信息可以让我们看看问题出在哪里好的,我明天在办公室的时候会试试。去年我用的是time.strtime,我得到了我需要的数据。对于db['collection']在这里,我可能会犯错误。无论如何,如果我明天完成工作,我会让你知道。谢谢。不幸的是,这也没有解决我的问题。我用你的代码完全更正了我的代码。它不返回任何结果。我的pymongo版本是3.0.1。你能告诉我你的pymongo版本吗,并用你的代码给出你的测试结果吗?谢谢。@Victor、 Li,你确定用户名确实存在于你的集合中吗?你能去MongoShell并尝试query justdb.collection.find({'username':'test')吗
并发布结果?使用datetime/time的原因不起作用,这意味着存储在mongo中的日期不完全是ISODate
对象,或者集合中不存在记录。我确信用户名存在,并且我确实从我的mongodb中按用户名或按datefrom&dateto查找结果。mong中显示的日期时间odb是ISODate。目前,我使用另一种方法,即首先通过usr_名称获取结果,然后迭代它们并检查日期时间。如果您知道有更好的方法来解决此难题,请在这里发布并让我们知道。干杯。@Victor.Li,您不断寻求帮助,但同时也假设代码的其他部分工作正常很好,这是我们无法帮助的,因为在本例中,您的数据中肯定存在错误。您需要显示您的mongo shell结果以及数据建模的准确方式。