简体   繁体   English

来自带有 Python 的时间戳的唯一 Object_id

[英]Unique Object_id from timestamp with Python

I am creating a collection in MongoDB using pymongo.我正在使用 pymongo 在 MongoDB 中创建一个集合。 The elements of the collection already have a creation_date and I would like to use that to create the _id field.集合的元素已经有一个 creation_date,我想用它来创建 _id 字段。 Since there is the possibility that more elements share the same creation_date, how can I create unique Object_id from that field?由于有可能更多元素共享相同的创建日期,我如何从该字段创建唯一的 Object_id?

bson has a function: bson.ObjectId.from_datetime(timestamp) which warns about the non uniqueness of the generated id. bson 有一个 function: bson.ObjectId.from_datetime(timestamp)警告生成的 id 的非唯一性。 Is there a way to add some randomness to it such that different object_ids are generated from the same date?有没有办法给它添加一些随机性,以便从同一日期生成不同的 object_ids?

The bson objectId return a 24 hex digits variable which the first 8 digits is depends on the time and the remaining digits are some random number. bson objectId 返回一个 24 位十六进制数字变量,其中前 8 位数字取决于时间,其余数字是一些随机数。 If you create an id by using bson.ObjectId.from_datetime(args) function, it returns a 24 hex digits variable which last 16 digits are zero.如果您使用 bson.ObjectId.from_datetime(args) function 创建一个 id,它会返回一个 24 位十六进制数字变量,最后 16 位数字为零。 By adding a random number to last part you can make it unique.通过在最后一部分添加一个随机数,您可以使其独一无二。 for generating random number you can use bson.objectId itself (last 16 digits)要生成随机数,您可以使用 bson.objectId 本身(最后 16 位数字)

ps: bason.objectId() returns a class instance and you should convert it into string. 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM