[英]How to get the Object_Id from COM Object in Enterprise Architect
[英]Unique Object_id from timestamp with Python
我正在使用 pymongo 在 MongoDB 中創建一個集合。 集合的元素已經有一個 creation_date,我想用它來創建 _id 字段。 由於有可能更多元素共享相同的創建日期,我如何從該字段創建唯一的 Object_id?
bson 有一個 function: bson.ObjectId.from_datetime(timestamp)
警告生成的 id 的非唯一性。 有沒有辦法給它添加一些隨機性,以便從同一日期生成不同的 object_ids?
bson objectId 返回一個 24 位十六進制數字變量,其中前 8 位數字取決於時間,其余數字是一些隨機數。 如果您使用 bson.ObjectId.from_datetime(args) function 創建一個 id,它會返回一個 24 位十六進制數字變量,最后 16 位數字為零。 通過在最后一部分添加一個隨機數,您可以使其獨一無二。 要生成隨機數,您可以使用 bson.objectId 本身(最后 16 位數字)
ps: bason.objectId() 返回一個 class 實例,你應該把它轉換成字符串。
import import time
from datetime import datetime
import bson
def uniqueTimeIdCreator(_time = time.time()):
date = datetime.fromtimestamp(_time)
timeId = str(bson.ObjectId.from_datetime(date))
uniqueId = str(bson.ObjectId())
return timeId[0:8] + uniqueId[8:]
def calc_time(_id):
_time = bson.ObjectId(_id).generation_time
return _time.strftime("%Y-%m-%d-%H-%M-%S")
specTime = time.time()
id1 = str(uniqueTimeIdCreator(specTime))
id2 = str(uniqueTimeIdCreator(specTime))
print(id1)
print(id2)
t1 = calc_time(id1)
t2 = calc_time(id2)
print(t1)
print(t2)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.