![](/img/trans.png)
[英]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.