ahawker / ulid

Universally Unique Lexicographically Sortable Identifier (ULID) in Python 3
Apache License 2.0
695 stars 42 forks source link

Allow adding `<Timestamp> + <Randomness>` to get full `<ULID>` #490

Open pirate opened 1 year ago

pirate commented 1 year ago

I originally was going to contribute a ulid.from_timestamp_and_randomness(timestamp, randomness) function, but I feel like this operator approach is more intuitive and concise:

import ulid
from blake3 import blake3
from datetime import datetime

some_data = 'https://example.com/some/test/page.html'
data_hash = blake3(some_data.encode()).hexdigest()[:16]
timestamp = datetime.fromisoformat('2023-03-14T05:04:21.452729')

ulid_timestamp = ulid.from_timestamp(timestamp).timestamp()      # <Timestamp('01GVFWNS6C')> 
ulid_randomness = ulid.from_randomness(data_hash).randomness()   # <Randomness('EF25CD4687E793CB')>

# equivalent to: ulid.from_bytes(ulid_timestamp.bytes + ulid_randomness.bytes)
final_ulid = ulid_timestamp + ulid_randomness

# <ULID('01GVFWNS6CEF25CD4687E793CB')>

Note: Please double check the mypy typing in my commit, you may need to quote the other: 'Randomness' type like how I quoted -> 'UUID', because the definition is below it in the file.


Thanks for an awesome project! ulid + blake3 is an amazing combo for hashing and indexing internet archiving snapshots in my upcoming ArchiveBox refactor 😄