Jundiaius
Jundiaius

Reputation: 7668

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?

Upvotes: 15

Views: 33980

Answers (4)

sedeh
sedeh

Reputation: 7313

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.

Upvotes: 26

zipa
zipa

Reputation: 27879

You can use datetime to create current timestamp:

import datetime
datetime.datetime.now().strftime('%Y%m%d%H%M%S')

Now you can concatenate that with anything you want.

If you want to add microseconds to make sure it is unique just add %f to the end:

datetime.datetime.now().strftime('%Y%m%d%H%M%S%f')

Upvotes: 9

Lix
Lix

Reputation: 47986

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

Upvotes: 7

ninesalt
ninesalt

Reputation: 4354

You can use a UUID, built in to the standard library. Specifically you can use a uuid4 just for a little extra security because it doesn't encode the computer's network address.

import uuid

print(uuid.uuid4()) #56d36372-b5ec-4321-93b8-939ee7d780aa

Upvotes: 0

Related Questions