Unique ID Generation using Time and Randomness

  • Share this:

Code introduction


This function generates a unique ID based on the current time and a random number, using the MD5 hashing algorithm and slicing.


Technology Stack : os, re, json, sys, time, datetime, hashlib, random

Code Type : Function

Code Difficulty : Intermediate


                
                    
import os
import re
import json
import sys
import time
import datetime
import hashlib
import random

def generate_unique_id(length=8):
    """Generate a unique ID based on current time and random number."""
    random_number = random.randint(0, 99999)
    current_time = datetime.datetime.now().strftime("%Y%m%d%H%M%S")
    unique_id = hashlib.md5(f"{current_time}{random_number}".encode()).hexdigest()[:length]
    return unique_id