私はdjango-nonrelとmongodbを使ってアプリを開発しています。オブジェクト ID は、オブジェクト作成の挿入時間のタイムスタンプで始まることを知っています。したがって、_id フィールドに基づいて時間範囲クエリを実行できます。
Pythonまたはdjangoで特定の時間に基づいて最小限のobject_idを生成するにはどうすればよいですか?
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))
私は最終的に解決策を見つけます。それが他の人に役立つことを願っています。
これは、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)