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)])


猜你喜欢

转载自blog.csdn.net/u011085172/article/details/80676066