pymongo 按日期时间查询

pymongo query by datetime

有一个问题让我头疼了将近一天

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 查询两个日期之间的数据?

这里有 2 个问题,您正试图在 数据库 对象上调用 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()
    ...

我还没有测试过,但它应该会按预期工作,希望这对您有所帮助。