Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create unique id based on date in Python

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?

like image 702
Jundiaius Avatar asked May 16 '18 10:05

Jundiaius


People also ask

How do you assign a unique ID in Python?

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.

How do you generate unique identifiers?

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.

Is ID unique in Python?

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.


2 Answers

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 eventids between two timestamps, say.

like image 66
sedeh Avatar answered Oct 25 '22 18:10

sedeh


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

like image 33
Lix Avatar answered Oct 25 '22 17:10

Lix