首页 > 代码库 > Python生成唯一id的方法

Python生成唯一id的方法

 

1.使用uuid

import uuiddef create_uid():    return str(uuid.uuid1())if __name__ == ‘__main__‘:    print(type(create_uid()))    print(create_uid())    print(create_uid())    print(create_uid())---<class ‘str‘>cdcb9030-51e8-11e7-881d-3c52824c8d6fcdcb9031-51e8-11e7-86b4-3c52824c8d6fcdcb9032-51e8-11e7-be6c-3c52824c8d6f

2.使用hashlib+time

  - 示例1:

import time,hashlibdef create_id():    m = hashlib.md5(str(time.clock()).encode(‘utf-8‘))    return m.hexdigest()if __name__ == ‘__main__‘:    print(type(create_id()))    print(create_id())    print(create_id())    print(create_id())---<class ‘str‘>b96d5fca757c00cbd53ae672f60e7ffe3e8391327caa4850077768d88ee18c7edf28a1e9895052608c2a6897f13d5659

  - 示例2:

import time,hashlibdef create_id():    m = hashlib.md5()    m.update(bytes(str(time.clock()),encoding=‘utf-8‘))    return m.hexdigest()if __name__ == ‘__main__‘:    print(type(create_id()))    print(create_id())    print(create_id())    print(create_id())---<class ‘str‘>be4a24bec22f46c84a4dde78e68cb83853e8e0c48c885b91fb2565cbe87b8423f8fd24c3b8ce1a39217134e22203a5c4

  

Python生成唯一id的方法