将Date对象放入MongoDB,在使用pymongo查询时返回浮点数

Ass*_*vie 5 python mongodb bson pymongo

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

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

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

{ "_id" : { "user" : "assaf", "day" : 1331769600000 }, "value" : { "count" : 15 } }
{ "_id" : { "user" : "assaf", "day" : 1331856000000 }, "value" : { "count" : 57 } }
Run Code Online (Sandbox Code Playgroud)

不知何故,日期看起来像一个整数 - 我想这是一些时间戳表示.如果我这样做:

PRIMARY> new Date(db.my_collection.find()[0]["_id"]["day"])
Run Code Online (Sandbox Code Playgroud)

我找回了正确的日期:

ISODate("2012-03-19T00:00:00Z")
Run Code Online (Sandbox Code Playgroud)

我的问题是如何在pymongo做同样的事情.如果我对上面的集合运行任何查询,pymongo将返回day值为float类型的文档,其值与timestamp相同:

dict: {u'_id': {u'user': u'ariel', u'day': 1332115200000.0}, u'value': {u'count': 99.0}}
Run Code Online (Sandbox Code Playgroud)

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

Qia*_*iau 6

从纪元(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)
>>>
Run Code Online (Sandbox Code Playgroud)

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

  • +1,但你应该将`1000`改为`1000.0`或从__future__ import division`添加`以避免整数除法,这会导致时间戳的毫秒精度. (2认同)