gpt4 book ai didi

python - 来自 Python 中 UTC 时间戳的 UUID1?

转载 作者:太空狗 更新时间:2023-10-30 02:49:39 25 4
gpt4 key购买 nike

问题是这样的:

我的应用程序部署在具有不同时区的远程服务器上,我想针对 UTC 时间戳生成一个 uuid1。我找不到从任何给定时间戳生成 uuid1 的方法。我想这样做的原因是我不想陷入计算本地时间的麻烦,因为我的本地时间不遵守夏令时,而远程服务器遵守夏令时,结果表示逻辑变得很麻烦。

限制是Timestamp需要存储为uuid1。对此的任何想法或解决方法将不胜感激。

最佳答案

如果您给它正确的片段,UUID 类将进行位杂耍 - http://docs.python.org/library/uuid.html

要获得正确的组件,您可以从 python2.7 复制 uuid1 代码:

def uuid1(node=None, clock_seq=None):
"""Generate a UUID from a host ID, sequence number, and the current time.
If 'node' is not given, getnode() is used to obtain the hardware
address. If 'clock_seq' is given, it is used as the sequence number;
otherwise a random 14-bit sequence number is chosen."""
# When the system provides a version-1 UUID generator, use it (but don't
# use UuidCreate here because its UUIDs don't conform to RFC 4122).
if _uuid_generate_time and node is clock_seq is None:
_buffer = ctypes.create_string_buffer(16)
_uuid_generate_time(_buffer)
return UUID(bytes=_buffer.raw)
global _last_timestamp
import time
nanoseconds = int(time.time() * 1e9)
# 0x01b21dd213814000 is the number of 100-ns intervals between the
# UUID epoch 1582-10-15 00:00:00 and the Unix epoch 1970-01-01 00:00:00.
timestamp = int(nanoseconds//100) + 0x01b21dd213814000L
if _last_timestamp is not None and timestamp <= _last_timestamp:
timestamp = _last_timestamp + 1
_last_timestamp = timestamp
if clock_seq is None:
import random
clock_seq = random.randrange(1<<14L) # instead of stable storage
time_low = timestamp & 0xffffffffL
time_mid = (timestamp >> 32L) & 0xffffL
time_hi_version = (timestamp >> 48L) & 0x0fffL
clock_seq_low = clock_seq & 0xffL
clock_seq_hi_variant = (clock_seq >> 8L) & 0x3fL
if node is None:
node = getnode()
return UUID(fields=(time_low, time_mid, time_hi_version,
clock_seq_hi_variant, clock_seq_low, node), version=1)

所有你需要做的就是复制+粘贴并修改时间戳部分以使用固定值(如果你知道你的时间是不同的,你可以忽略 last_timestamp 部分 - 这只是为了避免时钟分辨率为不足)。

关于python - 来自 Python 中 UTC 时间戳的 UUID1?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7153844/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com