简体   繁体   中英

Unique Object_id from timestamp with Python

I am creating a collection in MongoDB using pymongo. The elements of the collection already have a creation_date and I would like to use that to create the _id field. Since there is the possibility that more elements share the same creation_date, how can I create unique Object_id from that field?

bson has a function: bson.ObjectId.from_datetime(timestamp) which warns about the non uniqueness of the generated id. Is there a way to add some randomness to it such that different object_ids are generated from the same date?

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. 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. 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)

ps: bason.objectId() returns a class instance and you should convert it into string.

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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