2017-05-08 58 views
1

我想在python中激发一个查询来查找最后24小时注册用户。 在我的数据库如何在基于时间戳的MongoDB中查询

I have user profile data as: 

    {u'DOB': None, 
    u'_id': ObjectId('5906f3b.....'), 
    u'active': 0, 
    u'bfunc': 0, 
    u'city': None, 
    u'contact': u'', 

u'created':1493627839,根据创建了我如何才能找到最后的24个小时数据

u'email': u'[email protected] 
    u'facebook_id': u'', 
    u'fburl': None, 
    u'firstname': u'', 
    u'gender': None, 
    u'group_id': None} 

。 当我转换时间戳1493627839到日期它显示为2017-05-01 14:07:19

我这样做,但它找到0值。难道我做错了什么???或者有另一种方式。

 value = [] 
    timenow = datetime.datetime.now() 
    ltunix = timenow.strftime("%Y-%m-%d %H:%M:%S") #today 
    curTime = int(time.mktime(time.strptime(ltunix, '%Y-%m-%d %H:%M:%S'))) 
    gteTime = timenow - datetime.timedelta(days = 10) # last 10th day 
    getTimeUnix =gteTime.strftime("%Y-%m-%d %H:%M:%S") 
    earTime = int(time.mktime(time.strptime(getTimeUnix, '%Y-%m-%d %H:%M:%S'))) 
    cursor = collection.find({ 
     'created': {'$or':[ 
      {"$lt": curTime}, 
      {"$gte": earTime}] 
     } 
    }) 
    print cursor 

我在本例中搜索最近的10天。

回答

0

对于过去24小时:

{'created':{'$lt':datetime.datetime.now(), '$gt':datetime.datetime.now() - timedelta(hours=24)}} 

对于最近10天:

{'created':{'$lt':datetime.datetime.now(), '$gt':datetime.datetime.now() - timedelta(days=10)}} 
+0

它仍然显示为空。不工作。 – Vivek

+0

但它工作时,我转换成时间戳.... thnkx的方式 – Vivek

+0

很高兴它的工作! – Astro

0

您正在使用的纪元值存储在数据库中创建时间。您可以使用calendar模块将日期时间对象转换为纪元值,然后进行必要的比较。

now = calendar.timegm(datetime.datetime.now().timetuple()) 
then = calendar.timegm((datetime.datetime.now()-datetime.timedelta(hours=24)).timetuple()) 

result = collection.find({'created': {'$lt':now, '$gte':then}}) 
+0

我以前尝试过,但它的时间戳是diffr。所以我在我的情况下工作。 thnkx for responce – Vivek

+0

@Vivek,你的意思是说mongo文档中'created'字段不是UNIX纪元值吗? – yeniv

+1

我这么认为。 unix时代值是'2017-05-08T10:36:34Z',但我的值是'2017-05-01 14:07:19' – Vivek