2017-05-08 137 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