Reputation: 76113
I'm adding a date value into a MongoDB collection as part of a map-reduce call:
day = Date.UTC(this.time.getFullYear(), this.time.getMonth(), this.time.getDate());
emit({ user : this.user, day : day }, { count : 1 });
When I later query this collection in the Mongo shell I see:
{ "_id" : { "user" : "assaf", "day" : 1331769600000 }, "value" : { "count" : 15 } }
{ "_id" : { "user" : "assaf", "day" : 1331856000000 }, "value" : { "count" : 57 } }
Somehow the date looks like an integer - I guess it's some timestamp representation. If I do this:
PRIMARY> new Date(db.my_collection.find()[0]["_id"]["day"])
I get back the correct date:
ISODate("2012-03-19T00:00:00Z")
My question is how to do the same in pymongo. If I run any query on the above collection, pymongo returns documents in which the day
value as a float type with the same value as the timestamp:
dict: {u'_id': {u'user': u'ariel', u'day': 1332115200000.0}, u'value': {u'count': 99.0}}
How do I turn this timestamp into a Python datetime
?
Upvotes: 5
Views: 3425
Reputation: 7621
The title of the question is not the same as the code.
Date.UTC() returns a integer, not a date object. You are storing the integer and mongoDB is fine with that. Later, you pull the integer out and use it in the Date() construct and in the javascript environment this is all fine. But in python, it only sees the integer. The conversion posted earlier seems to be a good one.
Upvotes: 0
Reputation: 6175
Looks like milliseconds since epoch (1 Jan 1970):
>>> 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)
>>>
UPDATE: Added division check from first comment.
Upvotes: 6