python - 在 Python 中根据日期创建唯一 ID

标签 python python-3.x

在 MongoDb 中,为新文档自动分配的 ID (ObjectId) 是唯一的,并且在其内部包含其创建的时间戳。

在不使用任何库(除了 Python 的内置库)的情况下,我如何才能创建这种简洁的唯一 ID 并以某种方式保留其创建时间戳?

最佳答案

如果您有一个多线程或多机场景,那么所有的赌注都没有了,如果只使用时间戳,您不应该依赖任何“额外级别的唯一保证”。从 this excellent answer from deceze 阅读更多内容.

与上述答案类似,另一种选择是连接时间戳和 uuid:

from datetime import datetime
from uuid import uuid4

eventid = datetime.now().strftime('%Y%m-%d%H-%M%S-') + str(uuid4())
eventid
>>> '201902-0309-0347-3de72c98-4004-45ab-980f-658ab800ec5d'

eventid 包含 56 个字符,这对您来说可能是问题,也可能不是问题。但是,它包含创建时间戳并且是可排序的,所有这些在数据库中都是有利的,例如允许您查询两个时间戳之间的 eventid

关于python - 在 Python 中根据日期创建唯一 ID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50368143/

相关文章:

python - python中具有继承的动态类

python - 计算 Pandas 数据框中的日时差

Python 警告——如何不打印源代码行?

python - shell命令运行带有args的python脚本,args是一个列表

mysql - 如果我只在 aiomysql 中选择,我是否需要提交

python - 使用 wkhtmltopdf Django 生成 pdf

python - 如何更改 matplotlib 图的默认窗口位置?

python - 如何检查命令是否完成?

python - 类型错误 : cannot convert the series to <class 'float' >

python - 删除 'command not found' 错误 discord.py