【问题标题】:how to query in MongoDB based on timestamp如何根据时间戳在MongoDB中查询
【发布时间】:2017-05-08 04:56:57
【问题描述】:

我想在 python 中触发一个查询,以仅查找最近 24 小时的注册用户。 在我的数据库中

   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'',

你'创建':1493627839,

    u'email': u'mymail@demo.c
    u'facebook_id': u'',
    u'fburl': None,
    u'firstname': u'',
    u'gender': None,
    u'group_id': None}

基于我如何找到过去 24 小时数据而创建的。 当我将时间戳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 天。

【问题讨论】:

    标签: php python mongodb timestamp find


    【解决方案1】:

    过去 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)}}
    

    【讨论】:

      【解决方案2】:

      您正在使用 epoch 值将创建时间存储在数据库中。您可以使用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}})
      

      【讨论】:

      • 我之前试过这个,但它的时间戳是不同的。所以我在我的情况下工作。谢谢回复
      • @Vivek,你的意思是说mongo文档中的created字段不是UNIX epoch值吗?
      • 我想是的。 unix epoch 值是 2017-05-08T10:36:34Z 但我的值是 2017-05-01 14:07:19
      猜你喜欢
      • 2014-10-06
      • 2018-08-16
      • 1970-01-01
      • 1970-01-01
      • 2018-06-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-10-10
      相关资源
      最近更新 更多