Mongodb Time Range Request

advertisements

I'm using django-nonrel and mongodb to develop app. I know that object id is start with a timestamp of the insertion time of object creation. So it's possible to do time range query based on _id field.

How can I generate a minimal object_id based on a given time in python or django?


Here is a much more pythonic version of the other answer here provided by OP, along with documentation:

from bson.objectid import ObjectId
import datetime

def datetime_to_objectid(dt):
    # ObjectId is a 12-byte BSON type, constructed using:
    # a 4-byte value representing the seconds since the Unix epoch,
    # a 3-byte machine identifier,
    # a 2-byte process id, and
    # a 3-byte counter, starting with a random value.

    timestamp = int((dt - datetime.datetime(1970,1,1)).total_seconds())
    time_bytes = format(timestamp, 'x') #4 bytes
    return ObjectId(time_bytes+'00'*8) #+8 bytes

However, starting with version 1.6 of pymongo, it would be much more elegant to do the following:

from bson.objectid import ObjectId

ObjectId.from_datetime(dt)