snowflake.py 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. import datetime
  2. import time
  3. # twitter's snowflake parameters
  4. twepoch = 1288834974657
  5. datacenter_id_bits = 5
  6. worker_id_bits = 5
  7. sequence_id_bits = 12
  8. max_datacenter_id = 1 << datacenter_id_bits
  9. max_worker_id = 1 << worker_id_bits
  10. max_sequence_id = 1 << sequence_id_bits
  11. max_timestamp = 1 << (64 - datacenter_id_bits - worker_id_bits - sequence_id_bits)
  12. def make_snowflake(timestamp_ms, datacenter_id, worker_id, sequence_id, twepoch=twepoch):
  13. """generate a twitter-snowflake id, based on
  14. https://github.com/twitter/snowflake/blob/master/src/main/scala/com/twitter/service/snowflake/IdWorker.scala
  15. :param: timestamp_ms time since UNIX epoch in milliseconds"""
  16. sid = ((int(timestamp_ms) - twepoch) % max_timestamp) << datacenter_id_bits << worker_id_bits << sequence_id_bits
  17. sid += (datacenter_id % max_datacenter_id) << worker_id_bits << sequence_id_bits
  18. sid += (worker_id % max_worker_id) << sequence_id_bits
  19. sid += sequence_id % max_sequence_id
  20. return sid
  21. def melt(snowflake_id, twepoch=twepoch):
  22. """inversely transform a snowflake id back to its parts."""
  23. sequence_id = snowflake_id & (max_sequence_id - 1)
  24. worker_id = (snowflake_id >> sequence_id_bits) & (max_worker_id - 1)
  25. datacenter_id = (snowflake_id >> sequence_id_bits >> worker_id_bits) & (max_datacenter_id - 1)
  26. timestamp_ms = snowflake_id >> sequence_id_bits >> worker_id_bits >> datacenter_id_bits
  27. timestamp_ms += twepoch
  28. return timestamp_ms, int(datacenter_id), int(worker_id), int(sequence_id)
  29. def local_datetime(timestamp_ms):
  30. """convert millisecond timestamp to local datetime object."""
  31. return datetime.datetime.fromtimestamp(timestamp_ms / 1000.)
  32. def test():
  33. # print(local_datetime(t0))
  34. for i in range(0, 100):
  35. t0 = int(time.time() * 1000)
  36. print(make_snowflake(t0, 0, 0, 0))
  37. test()