Unique ID Generator with SHA-256 and Timestamp

  • Share this:

Code introduction


This function generates a unique ID based on the input string by combining the input string with the current timestamp and using the SHA-256 hashing algorithm to ensure uniqueness.


Technology Stack : hashlib, datetime

Code Type : Function

Code Difficulty : Intermediate


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

def generate_unique_id(input_string):
    """
    生成一个基于输入字符串的唯一的ID,使用hashlib和time戳。
    """
    # 将输入字符串与当前时间戳结合
    unique_string = input_string + str(datetime.datetime.now().timestamp())
    # 使用hashlib生成哈希值
    hash_object = hashlib.sha256(unique_string.encode())
    # 返回16进制格式的哈希值
    return hash_object.hexdigest()