Skip to content

Ramblings and Thoughts

  • About

Ramblings and Thoughts

Networking, Computers, Life

Code Snippet to generate a unique value

March 26, 2019 by cbogdon

In doing some basic database programming in Python, I always find the need to generate a unique value for key index. I have a few examples that would help:

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('=','')

Post navigation

Previous Post:

Python testing notes with pytest

Next Post:

How to leverage WTForms and Bootstrap Web Template

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Tags

Apache Carbon Copy Cloner Chrome Cisco Crashplan HTML iOS iClou Linux MySQL Nexus NXAPI Omnifocus OSX Outlook PyCharm Pytest Python Quicken Samsung TV Ubuntu VMWare Wordpress Youtube

Follow Us

Follow Us

© 2021 Ramblings and Thoughts | WordPress Theme by Superbthemes