【问题标题】:Finding document based on date range works in the mongodb shell, but not with pymongo基于日期范围查找文档在 mongodb shell 中有效,但不适用于 pymongo
【发布时间】:2014-12-21 23:30:34
【问题描述】:

在 mongo shell 上,它返回一个文档就好了:

> db.orderbook_log.findOne({'time': { '$gte': new Date(2014, 9, 24, 17, 38, 20, 546000), '$lt': new Date(2014, 10, 24, 17, 39, 20, 546000)}})

    //... returns document with this time stamp:
    "time" : ISODate("2014-10-25T00:47:30.819Z")

请注意,我在 10 月使用了“9”,因为 JavaScript 的月份是 0-11。 而且我还用“23”作为天进行了测试,因为看起来 JS 天也是 0-indexed,并且还返回了一个文档:"time" : ISODate("2014-10-24T17:32:13.595Z")

atime = datetime.datetime(2014, 10, 24, 17, 38, 20, 546000)
btime =  datetime.datetime(2014, 10, 24, 17, 39, 20, 546000)

future_book = log.find_one({"time": {"$gte": atime, "$lt": btime}})

但是当我在 pymongofuture_book 中执行 find_one 时是 None

我真正想做的只是循环前 100 条左右的记录,然后获取相对一分钟后发生的记录。

【问题讨论】:

    标签: mongodb datetime pymongo


    【解决方案1】:

    Javascript 天不是零索引的,唉。只有几个月。

    我在您的 Javascript 中看到您将 546,000 毫秒添加到第一个日期,因此结果为 2014 年 10 月 24 日 17:48:26。 Javascript 然后转换为您的本地时区,因此在我的情况下它增加了 5 小时:

    > new Date(2014, 10, 24, 17, 39, 20, 546000)
    ISODate("2014-11-24T22:48:26Z")
    

    然后将其与文档中的“时间”字段进行比较(忽略时区)。

    最好去掉最后的毫秒参数,使用MongoDB shell的ISODate函数,比Javascript Dates设计的更合理:

    > ISODate('2014-10-24T17:38:20')
    ISODate("2014-10-24T17:38:20Z")
    

    然后它将以您期望的方式与您的文档进行比较,并且它应该匹配 PyMongo 行为。我建议您也从 Python 日期时间构造函数中删除毫秒参数,以澄清事情。

    【讨论】:

      猜你喜欢
      • 2013-04-10
      • 1970-01-01
      • 2017-02-27
      • 2013-04-05
      • 1970-01-01
      • 1970-01-01
      • 2021-02-24
      • 2019-01-25
      • 2023-02-08
      相关资源
      最近更新 更多