In MongoDb the automatically assigned id (ObjectId) for new documents is unique and contains within itself the timestamp of its creation.
Without using any library (other than built-in libs of Python), how can I create this type of concise unique ids that also somehow holds its timestamp of creation?
creating a unique random id To create a random id, you call the uuid4 () method and it will automatically generate a unique id for you just as shown in the example below; Example of usage.
The simplest way to generate identifiers is by a serial number. A steadily increasing number that is assigned to whatever you need to identify next. This is the approached used in most internal databases as well as some commonly encountered public identifiers.
The id() function returns a unique id for the specified object. All objects in Python has its own unique id. The id is assigned to the object when it is created.
If you have a multithreaded or multi-machine scenario, all bets are off and you should not rely on any "extra level of unique assurance" if using timestamp only. Read more from this excellent answer from deceze.
Similar to above answers, another option is to concatenate timestamp and uuid:
from datetime import datetime
from uuid import uuid4
eventid = datetime.now().strftime('%Y%m-%d%H-%M%S-') + str(uuid4())
eventid
>>> '201902-0309-0347-3de72c98-4004-45ab-980f-658ab800ec5d'
eventid
contains 56 characters which may or may not be an issue for you. However, it holds timestamp of creation and is sortable all of which could be advantageous in a database allowing you to query eventid
s between two timestamps, say.
Using an epoch timestamp with a sufficient amount of precision might just be enough for you. Combine this with a simple user id and you'll have yourself a unique ID with a timestamp embedded into it:
import time
epoch = time.time()
user_id = 42 # this could be incremental or even a uuid
unique_id = "%s_%d" % (user_id, epoch)
unique_id
will now have a value similar to 42_1526466157
. You can take this value and split it by the _
character - now you have the original epoch of creation time (1526466157).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With