Code Snippet to generate a unique value
In doing some basic database programming in Python, I always find the need to generate a unique value for
Sequential Index
This example will generate a sequential number based on the current date and time:
time.strftime("%Y%j%H%M")+str(time.process_time_ns()//1000)
$ python3
Python 3.7.2 (default, Feb 12 2019, 08:15:36)
[Clang 10.0.0 (clang-1000.11.45.5)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import time
>>> int(time.strftime("%Y%j%H%M")+str(time.process_time_ns()//1000))
2019085124932816
>>> int(time.strftime("%Y%j%H%M")+str(time.process_time_ns()//1000))
2019085124933782
Non Sequential Random Numbers
This example creates a uuid number unique. It is pretty useful when you don’t need a sequential number
def get_a_uuid():
"""
@return: returns a uuid
This functions returns a unique uuid that can be used as indexing values.
"""
r_uuid = base64.urlsafe_b64encode(uuid.uuid4().bytes)
return str(r_uuid.decode('utf-8')).replace('=','')