15

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?

Jundiaius
  • 6,214
  • 3
  • 30
  • 43

4 Answers4

24

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.

sedeh
  • 7,083
  • 6
  • 48
  • 65
8

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')
zipa
  • 27,316
  • 6
  • 40
  • 58
  • 1
    I like the idea of being able to have the timestamp human readable +1! I think that adding the microseconds is a must though to add an extra level of unique assurance. – Lix May 16 '18 at 10:35
6

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

Lix
  • 47,311
  • 12
  • 103
  • 131
0

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
ninesalt
  • 4,054
  • 5
  • 35
  • 75
  • 2
    Where is the timestamp here? Please take another look at the OP's requirements - they need an id based on time – Lix May 16 '18 at 10:23
  • Is it possible to extract the timestamp from the id generated with this method? – Jundiaius May 16 '18 at 12:01