Mongodb中的时间范围查询

时间:2013-02-07 06:51:42

标签: django mongodb pymongo

我正在使用django-nonrel和mongodb来开发app。我知道对象id以对象创建的插入时间的时间戳开始。因此,可以根据_id字段进行时间范围查询。

如何根据python或django中的给定时间生成最小的object_id?

2 个答案:

答案 0 :(得分:0)

from bson.objectid import ObjectId
import time

def get_minimal_object_id_for_int_timestamp(int_timestamp=None):
    if not int_timestamp:
        int_timestamp=int(time.time())
    return ObjectId(hex(int(int_timestamp))[2:]+'0000000000000000')

def get_int_timestamp_from_time_string(time_string=None): 

    # format "YYYY-MM-DD hh:mm:ss" like '2012-01-05 13:01:51'
    if not time_string:
        return int(time.time())
    return int(time.mktime(time.strptime(time_string, '%Y-%m-%d %H:%M:%S')))

def get_minimal_object_id_for_time_string(time_string=None):
    return get_minimal_object_id_for_int_timestamp(get_int_timestamp_from_time_string(time_string=time_string))

我终于找到了解决方案。希望它对其他人有所帮助。

答案 1 :(得分:0)

这是OP提供的另一个答案的更加pythonic版本,以及文档:

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

然而,从pymongo的1.6版开始,执行以下操作会更优雅:

from bson.objectid import ObjectId

ObjectId.from_datetime(dt)