Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extract the time from a UUID v1 in python

Tags:

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.

like image 981
cdecker Avatar asked Sep 25 '10 21:09

cdecker


People also ask

How long is Python UUID?

The UUID as a 32-character lowercase hexadecimal string.

How do I get the UUID in Python?

UUID 1 to Generate a unique ID using MAC AddressThe uuid. uuid1() function is used to generate a UUID from the host ID, sequence number, and the current time. It uses the MAC address of a host as a source of uniqueness.

How do you use UUID in Python?

The uuid module provides immutable UUID objects (the UUID class) and the functions uuid1() , uuid3() , uuid4() , uuid5() for generating version 1, 3, 4, and 5 UUIDs as specified in RFC 4122. If all you want is a unique ID, you should probably call uuid1() or uuid4() .

What is the UUID function in Python?

UUID, Universal Unique Identifier, is a python library which helps in generating random objects of 128 bits as ids. It provides the uniqueness as it generates ids on the basis of time, Computer hardware (MAC etc.).


2 Answers

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 

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

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

So use:

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) 

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

like image 115
unutbu Avatar answered Oct 24 '22 14:10

unutbu


You could use a simple formula that follows directly from the definition:

The timestamp is a 60-bit value. For UUID version 1, this is represented by Coordinated Universal Time (UTC) as a count of 100- nanosecond intervals since 00:00:00.00, 15 October 1582 (the date of Gregorian reform to the Christian calendar).

>>> from uuid import uuid1 >>> from datetime import datetime, timedelta >>> datetime(1582, 10, 15) + timedelta(microseconds=uuid1().time//10) datetime.datetime(2015, 11, 13, 6, 59, 12, 109560) 
like image 31
jfs Avatar answered Oct 24 '22 12:10

jfs