Python 生成16位唯一ID/UUID

# -*- coding:utf-8 -*-
import time


class UUID:
    def __init__(self, data_id=0):
        """
        :param data_id: 自定义项目id
        """
        self.data_id = data_id
        self.now = int(time.time())
        self.UUID = 0

    @staticmethod
    def as_stamp(hms):
        raw_time = time.strptime(f"1970-01-02 {hms}", "%Y-%m-%d %H:%M:%S")
        return str(int(time.mktime(raw_time) - 86400)).zfill(5)

    def uuid(self):  # 代码顺序不能调整
        """ [6位年月日][4位自增序号][1位项目ID][5位一天内的时间戳] 共16位组成
        :return: 百年内唯一id
        """
        number = str(self.generate_num()).zfill(4)  # 秒内自增序号(max9999)
        date_tuple = time.localtime(self.now)  # 时间戳转时间元组
        hms_stamp = self.as_stamp(time.strftime("%H:%M:%S", date_tuple))  # 把时分秒转为时间戳
        ymd = time.strftime("%y%m%d", date_tuple)  # 年月日
        return f'{ymd}{number}{self.data_id}{hms_stamp}'

    def generate_num(self):
        now = int(time.time())
        if self.now == now:  # 时间差在1秒内序号自增
            self.UUID += 1
        else:  # 不同时间差,序列号重新置为0
            self.UUID = 0
            self.now = now
        if self.UUID == 9999:  # 序号长度不足,等待一秒
            time.sleep(1)
            return self.generate_num()  # 返回自己重新来过
        return self.UUID


if __name__ == '__main__':
    obj = UUID()
    while True:
        print(obj.uuid())

你可能感兴趣的:(Windows,开发,python,uuid,timestamp)