【问题标题】:Putting a Date object into MongoDB, getting back a float when querying with pymongo将日期对象放入 MongoDB,使用 pymongo 查询时返回浮点数
【发布时间】:2012-09-02 04:46:43
【问题描述】:

我正在将日期值添加到 MongoDB 集合中,作为 map-reduce 调用的一部分:

day = Date.UTC(this.time.getFullYear(), this.time.getMonth(), this.time.getDate());
emit({ user : this.user, day : day }, { count : 1 });

当我稍后在 Mongo shell 中查询这个集合时,我看到:

{ "_id" : { "user" : "assaf", "day" : 1331769600000 }, "value" : { "count" : 15 } }
{ "_id" : { "user" : "assaf", "day" : 1331856000000 }, "value" : { "count" : 57 } }

不知何故,日期看起来像一个整数——我猜它是某种时间戳表示。 如果我这样做:

PRIMARY> new Date(db.my_collection.find()[0]["_id"]["day"])

我找回了正确的日期:

ISODate("2012-03-19T00:00:00Z")

我的问题是如何在 pymongo 中做同样的事情。如果我对上述集合运行任何查询,pymongo 会返回其中 day 值作为浮点类型且与时间戳具有相同值的文档:

dict: {u'_id': {u'user': u'ariel', u'day': 1332115200000.0}, u'value': {u'count': 99.0}}

如何将此时间戳转换为 Python datetime

【问题讨论】:

    标签: python mongodb pymongo bson


    【解决方案1】:

    自纪元(1970 年 1 月 1 日)以来的毫秒数:

    >>> from __future__ import division
    >>> dict = {u'_id': {u'user': u'ariel', u'day': 1332115200000.0}, u'value': {u'count': 99.0}}
    >>> datetime.datetime.utcfromtimestamp(dict['_id']['day'] / 1000.0)
    datetime.datetime(2012, 3, 19, 0, 0)
    >>>
    

    更新:从第一条评论中添加了部门检查。

    【讨论】:

    • +1,但是您应该将1000 更改为1000.0 或添加from __future__ import division 以避免整数除法,这会破坏时间戳的毫秒精度。
    • 这行得通。知道为什么类型信息会在此过程中丢失吗?
    • 哦等等,来自 pymongo 的值是一个浮点数——所以我之前的评论不适用。不过,我想,明确表达总比依赖知识好。
    【解决方案2】:

    题名和代码不一样

    Date.UTC() 返回一个整数,而不是日期对象。 您正在存储整数,而 mongoDB 对此很好。 稍后,您将整数取出并在 Date() 构造和 javascript 环境中使用它,这一切都很好。 但是在python中,它只看到整数。 之前发布的转换似乎是一个不错的转换。

    【讨论】:

      猜你喜欢
      • 2012-08-11
      • 2014-12-09
      • 1970-01-01
      • 2016-09-25
      • 1970-01-01
      • 1970-01-01
      • 2016-02-11
      相关资源
      最近更新 更多