当前位置:主页 > 软件编程 > Python代码 >

python 根据时间来生成唯一的字符串方法

时间:2021-08-31 09:59:47 | 栏目:Python代码 | 点击:

我们很多时候,特别是在生成任务的时候,都需要一个唯一标识字符串来标识这个任务,比较常用的有生成uuid或者通过时间来生成。uuid的话可以直接通过uuid模块来生成。如果是时间的话,可以这么写:

def tid_maker():
 return '{0:%Y%m%d%H%M%S%f}'.format(datetime.datetime.now())

这里的时间精确到了微妙,一般来说不会重复,如果想更安全点,可以在后面多加几个随机字符,例如:

def tid_maker():
 return '{0:%Y%m%d%H%M%S%f}'.format(datetime.datetime.now())+''.join([str(random.randint(1,10)) for i in range(5)])

您可能感兴趣的文章:

相关文章