0
我正在使用django-nonrel和mongodb開發應用程序。我知道對象ID是以對象創建插入時間的時間戳開始的。所以可以根據_id字段進行時間範圍查詢。MongoDB中的時間範圍查詢
如何根據python或django中給定的時間生成最小的object_id?
我正在使用django-nonrel和mongodb開發應用程序。我知道對象ID是以對象創建插入時間的時間戳開始的。所以可以根據_id字段進行時間範圍查詢。MongoDB中的時間範圍查詢
如何根據python或django中給定的時間生成最小的object_id?
這裏是一個更Python的版本在這裏由OP提供的其他答案,以及文檔:
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)
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))
我終於找到解決方案了。希望它對別人有幫助。