从python中的UUID v1中提取时间 [英] Extract the time from a UUID v1 in python

查看:35
本文介绍了从python中的UUID v1中提取时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的程序中随机生成了一些 UUID,但我希望能够提取生成的 UUID 的时间戳以进行测试.我注意到使用 fields 访问器可以获得时间戳的各个部分,但我不知道如何组合它们.

I have some UUIDs that are being generated in my program at random, but I want to be able to extract the timestamp of the generated UUID for testing purposes. I noticed that using the fields accessor I can get the various parts of the timestamp but I have no idea on how to combine them.

推荐答案

查看/usr/lib/python2.6/uuid.py 你会看到

Looking inside /usr/lib/python2.6/uuid.py you'll see

def uuid1(node=None, clock_seq=None):
    ...
    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

求解 time.time() 的方程,你会得到

solving the equations for time.time(), you'll get

time.time()-like quantity = ((timestamp - 0x01b21dd213814000L)*100/1e9)

所以使用:

In [3]: import uuid

In [4]: u = uuid.uuid1()

In [58]: datetime.datetime.fromtimestamp((u.time - 0x01b21dd213814000L)*100/1e9)
Out[58]: datetime.datetime(2010, 9, 25, 17, 43, 6, 298623)

这给出了与 uuid.uuid1 生成的 UUID 相关联的日期时间.

This gives the datetime associated with a UUID generated by uuid.uuid1.

这篇关于从python中的UUID v1中提取时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆