generate a unique number in python

There are several ways to generate a unique number in Python. One commonly used method is to combine the current timestamp with a random number. Here's an example using the random module:

main.py
import random
import time

def generate_unique_number():
    timestamp = int(time.time()) # Get current timestamp
    random_number = random.randint(0, 9999) # Generate random number
    unique_number = f"{timestamp}_{random_number}" # Combine timestamp and random number
    return unique_number
297 chars
9 lines

In this example, the generate_unique_number() function returns a unique number in the format of <timestamp>_<random_number>. The timestamp ensures uniqueness by including the current time, while the random number adds an additional factor.

Note that this approach is not guaranteed to produce completely unique numbers, especially if called rapidly in succession. However, for most use cases, it should provide sufficient uniqueness.

related categories

gistlibby LogSnag