### Install Svix-KSUID Source: https://github.com/svix/python-ksuid/blob/main/README.md Install the library using pip. This is the first step before importing and using the Ksuid classes. ```bash pip install svix-ksuid ``` -------------------------------- ### Install svix-ksuid Source: https://context7.com/svix/python-ksuid/llms.txt Install the library using pip or uv. Requires Python 3.10+. ```bash pip install svix-ksuid ``` ```bash uv add svix-ksuid ``` -------------------------------- ### Extract Unix timestamp from Ksuid Source: https://context7.com/svix/python-ksuid/llms.txt Access the `.timestamp` property to get the creation time as a Unix timestamp `float`. This property has 1-second resolution for `Ksuid` and ~4ms resolution for `KsuidMs`. ```python from ksuid import Ksuid k = Ksuid() ts = k.timestamp print(ts) # e.g. 1621627443.0 print(type(ts)) # # Reconstruct from timestamp using datetime from datetime import datetime, timezone dt = datetime.fromtimestamp(ts, tz=timezone.utc) k2 = Ksuid(datetime=dt) assert k2.timestamp == k.timestamp ``` -------------------------------- ### Extract embedded UTC datetime from Ksuid Source: https://context7.com/svix/python-ksuid/llms.txt Access the `.datetime` property to get a timezone-aware `datetime` object in UTC. The precision is 1 second for `Ksuid` and ~4 milliseconds for `KsuidMs`. ```python from ksuid import Ksuid k = Ksuid() dt = k.datetime print(dt) # datetime.datetime(2024, 6, 10, 9, 45, 22, tzinfo=datetime.timezone.utc) print(dt.year) # 2024 print(dt.tzinfo) # UTC ``` -------------------------------- ### Order Ksuid Instances Source: https://github.com/svix/python-ksuid/blob/main/README.md Demonstrates the comparison operators for KSUIDs, showing that KSUIDs can be ordered based on their creation time. A KSUID created later will be greater than one created earlier. ```python from ksuid import Ksuid ksuid_1 = Ksuid() ksuid_2 = Ksuid() ksuid_1 < ksuid_2 ksuid_1 <= ksuid_2 ksuid_1 >= ksuid_2 ksuid_1 > ksuid_2 ``` -------------------------------- ### Create Ksuid from Bytes Source: https://github.com/svix/python-ksuid/blob/main/README.md Shows how to create a KSUID object from its byte representation and confirms that it is equal to the original KSUID. ```python from ksuid import Ksuid ksuid = Ksuid() ksuid_from_bytes = ksuid.from_bytes(bytes(ksuid)) ksuid == ksuid_from_bytes ``` -------------------------------- ### Initialize Default Ksuid Source: https://github.com/svix/python-ksuid/blob/main/README.md Import and instantiate the Ksuid class to generate a new KSUID with default settings. This KSUID will be based on the current time. ```python from ksuid import Ksuid ksuid = Ksuid() ``` -------------------------------- ### Create Ksuid from Base62 String Source: https://github.com/svix/python-ksuid/blob/main/README.md Demonstrates creating a KSUID object from its Base62 string representation and verifying its timestamp. ```python from ksuid import Ksuid ksuid = Ksuid() ksuid_from_base62 = Ksuid.from_base62("1srdszO8Xy2cR6CnARnvxCfRmK4") ksuid_from_base62.timestamp ``` -------------------------------- ### Compare Ksuid Instances Source: https://github.com/svix/python-ksuid/blob/main/README.md Illustrates that two KSUIDs generated from the same byte representation are equal. The output shows identical Base62 strings for both instances. ```python from ksuid import Ksuid ksuid_1 = Ksuid() ksuid_2 = Ksuid.from_bytes(bytes(ksuid_1)) ksuid_1 == ksuid_2 ``` -------------------------------- ### Generate and Inspect Default Ksuid Source: https://github.com/svix/python-ksuid/blob/main/README.md Demonstrates generating a KSUID without a specific datetime and inspecting its Base62 representation, byte format, datetime, timestamp, and payload. ```python from ksuid import Ksuid ksuid = Ksuid() f"Base62: {ksuid}" f"Bytes: {bytes(ksuid)}" f"Datetime: {ksuid.datetime}" f"Timestamp: {ksuid.timestamp}" f"Payload: {ksuid.payload}" ``` -------------------------------- ### .timestamp Source: https://context7.com/svix/python-ksuid/llms.txt Property that returns the creation time as a Unix timestamp `float`. For `Ksuid` this is a whole-number float (1-second resolution); for `KsuidMs` it carries fractional seconds with ~4ms resolution. ```APIDOC ## .timestamp ### Description Extracts the creation time as a Unix timestamp float. ### Property `timestamp` (float) ### Usage ```python from ksuid import Ksuid k = Ksuid() ts = k.timestamp print(ts) # e.g. 1621627443.0 print(type(ts)) # # Reconstruct from timestamp using datetime from datetime import datetime, timezone dt = datetime.fromtimestamp(ts, tz=timezone.utc) k2 = Ksuid(datetime=dt) assert k2.timestamp == k.timestamp ``` ### Response - `float`: The Unix timestamp representing the KSUID's creation time. Has 1-second resolution for `Ksuid` and ~4ms resolution for `KsuidMs`. ``` -------------------------------- ### Initialize KsuidMs for Higher Accuracy Source: https://github.com/svix/python-ksuid/blob/main/README.md Import and instantiate the KsuidMs class to generate a new KSUID with millisecond accuracy. This class sacrifices one byte of the random payload for improved timestamp precision. ```python from ksuid import KsuidMs ksuid = KsuidMs() ``` -------------------------------- ### KSUID Comparison and Ordering Source: https://context7.com/svix/python-ksuid/llms.txt KSUIDs support standard comparison operators (`==`, `<`, `>`) for chronological sorting and set membership. IDs created later are always greater due to the timestamp in the most significant bytes. This allows for efficient range queries and chronological pagination. ```python from ksuid import Ksuid from datetime import datetime, timedelta, timezone base = datetime(2024, 1, 1, tzinfo=timezone.utc) k1 = Ksuid(datetime=base) k2 = Ksuid(datetime=base + timedelta(hours=1)) k3 = Ksuid(datetime=base + timedelta(hours=1)) # same second as k2, different payload assert k1 < k2 assert k2 > k1 assert k1 != k2 assert k2 != k3 # different random payload # Sort a list of KSUIDs chronologically ids = [k2, k3, k1] sorted_ids = sorted(ids) assert sorted_ids[0] == k1 # oldest first # Use in sets and dicts (hashable) id_set = {k1, k2, k3} assert len(id_set) == 3 id_map = {k1: "event_a", k2: "event_b"} print(id_map[k1]) # 'event_a' ``` -------------------------------- ### Ksuid.from_base62(data) Source: https://context7.com/svix/python-ksuid/llms.txt Class method that reconstructs a `Ksuid` instance from its 27-character base62 string representation. Useful for parsing IDs stored in databases, passed over HTTP, or received from other KSUID-compatible systems. ```APIDOC ## Ksuid.from_base62(data) ### Description Reconstructs a `Ksuid` instance from its base62 string representation. ### Method `classmethod Ksuid.from_base62(data: str)` ### Parameters - **data** (str): The 27-character base62 string representation of the KSUID. ### Request Example ```python from ksuid import Ksuid original = Ksuid() b62 = str(original) # '1srdszO8Xy2cR6CnARnvxCfRmK4' restored = Ksuid.from_base62(b62) assert restored == original ``` ### Response #### Success Response - `Ksuid`: A `Ksuid` instance reconstructed from the base62 string. ``` -------------------------------- ### Generate a new Ksuid Source: https://context7.com/svix/python-ksuid/llms.txt Creates a new KSUID with the current UTC timestamp and a random payload. You can also specify a datetime and/or a custom 16-byte payload. The KSUID can be converted to a base62 string, raw bytes, or its timestamp and datetime can be accessed. ```python from datetime import datetime, timezone from ksuid import Ksuid # 1. Generate with current time and random payload k = Ksuid() print(str(k)) # e.g. '1srOrx2ZWZBpBUvZwXKQmoEYga2' (27 chars, base62) print(k.timestamp) # e.g. 1621627443.0 (Unix timestamp, float) print(k.datetime) # e.g. datetime.datetime(2021, 5, 21, 14, 4, 3, tzinfo=timezone.utc) print(bytes(k)) # b'\r5\xc43\xe1\x93>7\xf2up\x87c\xad\xc7tZ\xf5\xe7\xf2' (20 bytes) print(k.payload) # b'\xe1\x93>7\xf2up\x87c\xad\xc7tZ\xf5\xe7\xf2' (16-byte random part) # 2. Generate with a specific datetime (microseconds are truncated to seconds) dt = datetime(2024, 1, 15, 12, 0, 0, tzinfo=timezone.utc) k_fixed = Ksuid(datetime=dt) print(k_fixed.datetime) # datetime.datetime(2024, 1, 15, 12, 0, 0, tzinfo=timezone.utc) # 3. Generate with a custom payload (must be exactly 16 bytes) import os custom_payload = os.urandom(Ksuid.PAYLOAD_LENGTH_IN_BYTES) # 16 bytes k_custom = Ksuid(datetime=dt, payload=custom_payload) assert k_custom.payload == custom_payload ``` -------------------------------- ### Create Ksuid from Datetime Source: https://github.com/svix/python-ksuid/blob/main/README.md Generates a KSUID from a specific datetime object. Note that the microseconds are truncated to match the KSUID's second-level precision. ```python from datetime import datetime from ksuid import Ksuid datetime_obj = datetime(year=2021, month=5, day=19, hour=1, minute=1, second=1, microsecond=1) ksuid = Ksuid(datetime_obj) ksuid.datetime ksuid.timestamp ``` -------------------------------- ### Ksuid() — Generate a new KSUID Source: https://context7.com/svix/python-ksuid/llms.txt Creates a new KSUID with the current UTC timestamp and a cryptographically random 16-byte payload. Optionally accepts a `datetime` and/or a custom `payload` to fix those components. The resulting object serializes to a 27-character base62 string, and its `.timestamp` property returns a Unix timestamp float (1-second accuracy). ```APIDOC ## Ksuid() ### Description Generates a new KSUID with the current UTC timestamp and a random 16-byte payload. Allows specifying a `datetime` and/or a custom `payload`. ### Usage ```python from datetime import datetime, timezone from ksuid import Ksuid # Generate with current time and random payload k = Ksuid() print(str(k)) # e.g. '1srOrx2ZWZBpBUvZwXKQmoEYga2' print(k.timestamp) # e.g. 1621627443.0 print(k.datetime) # e.g. datetime.datetime(2021, 5, 21, 14, 4, 3, tzinfo=timezone.utc) print(bytes(k)) # b'\r5\xc43\xe1\x93>7\xf2up\x87c\xad\xc7tZ\xf5\xe7\xf2' print(k.payload) # b'\xe1\x93>7\xf2up\x87c\xad\xc7tZ\xf5\xe7\xf2' # Generate with a specific datetime dt = datetime(2024, 1, 15, 12, 0, 0, tzinfo=timezone.utc) k_fixed = Ksuid(datetime=dt) print(k_fixed.datetime) # datetime.datetime(2024, 1, 15, 12, 0, 0, tzinfo=timezone.utc) # Generate with a custom payload (must be exactly 16 bytes) import os custom_payload = os.urandom(Ksuid.PAYLOAD_LENGTH_IN_BYTES) # 16 bytes k_custom = Ksuid(datetime=dt, payload=custom_payload) assert k_custom.payload == custom_payload ``` ### Parameters - `datetime` (datetime, optional): The timestamp to embed in the KSUID. Microseconds are truncated to seconds. - `payload` (bytes, optional): A custom 16-byte payload. If not provided, a random payload is generated. ``` -------------------------------- ### Millisecond-Accuracy KSUID Generation Source: https://context7.com/svix/python-ksuid/llms.txt Use `KsuidMs` for sub-second ordering, extending the timestamp to 5 bytes with 4ms resolution. It generates a standard 27-character base62 string, interoperable with `Ksuid`. This is useful for high-throughput scenarios like financial transactions or telemetry. ```python from ksuid import KsuidMs from datetime import datetime, timezone # Generate with current time — sub-second precision preserved to ~4ms k = KsuidMs() print(str(k)) # '1sreAHoz6myPhXghsOdVBoec3Vr' (27-char base62, same format as Ksuid) print(k.timestamp) # e.g. 1621634852.124 (fractional seconds, ~4ms accuracy) print(k.datetime) # datetime with millisecond component # Round-trip via base62 restored = KsuidMs.from_base62(str(k)) assert restored.timestamp == k.timestamp # Round-trip via bytes restored_bytes = KsuidMs.from_bytes(bytes(k)) assert restored_bytes == k # Precision: timestamps are quantised to the nearest 4ms import math from datetime import timedelta t = datetime(2024, 6, 1, 0, 0, 0, 187499, tzinfo=timezone.utc) km = KsuidMs(datetime=t) # Both 187.499ms and 187.501ms round to the same 4ms bucket (184ms) assert math.floor(t.timestamp() * 250) == math.floor(km.datetime.timestamp() * 250) ``` -------------------------------- ### Deserialize Ksuid from base62 string Source: https://context7.com/svix/python-ksuid/llms.txt Reconstructs a Ksuid instance from its 27-character base62 string representation. This is useful for parsing IDs stored in databases or passed over HTTP. ```python from ksuid import Ksuid original = Ksuid() b62 = str(original) # '1srdszO8Xy2cR6CnARnvxCfRmK4' restored = Ksuid.from_base62(b62) assert restored == original assert restored.timestamp == original.timestamp assert restored.payload == original.payload print(f"Restored timestamp: {restored.timestamp}") # 1621634852.0 print(f"Restored datetime: {restored.datetime}") # datetime.datetime(...) ``` -------------------------------- ### .datetime Source: https://context7.com/svix/python-ksuid/llms.txt Property that decodes the timestamp portion of the KSUID and returns a timezone-aware `datetime` object in UTC. For `Ksuid` the precision is 1 second; for `KsuidMs` the precision is 4 milliseconds. ```APIDOC ## .datetime ### Description Extracts the embedded UTC datetime from the KSUID. ### Property `datetime` (datetime) ### Usage ```python from ksuid import Ksuid k = Ksuid() dt = k.datetime print(dt) # datetime.datetime(2024, 6, 10, 9, 45, 22, tzinfo=datetime.timezone.utc) print(dt.year) # 2024 print(dt.tzinfo) # UTC ``` ### Response - `datetime`: A timezone-aware `datetime` object in UTC. Precision is 1 second for `Ksuid` and ~4 milliseconds for `KsuidMs`. ``` -------------------------------- ### Ksuid.from_bytes(value) Source: https://context7.com/svix/python-ksuid/llms.txt Class method that reconstructs a `Ksuid` from a 20-byte `bytes` object (4-byte big-endian timestamp + 16-byte payload). Raises `ByteArrayLengthException` if the input is not exactly 20 bytes. ```APIDOC ## Ksuid.from_bytes(value) ### Description Reconstructs a `Ksuid` instance from a 20-byte `bytes` object. ### Method `classmethod Ksuid.from_bytes(value: bytes)` ### Parameters - **value** (bytes): A 20-byte `bytes` object containing the timestamp and payload. ### Request Example ```python from ksuid import Ksuid, ByteArrayLengthException original = Ksuid() raw = bytes(original) # 20-byte bytes object restored = Ksuid.from_bytes(raw) assert restored == original print(f"Round-trip OK: {restored}") # '1sreAHoz6myPhXghsOdVBoec3Vr' # Error handling for invalid byte length try: Ksuid.from_bytes(b'\x00' * 10) except ByteArrayLengthException as e: print(f"Error: {e}") # Error: Incorrect value length 10 ``` ### Response #### Success Response - `Ksuid`: A `Ksuid` instance reconstructed from the bytes. #### Error Response - `ByteArrayLengthException`: Raised if the input `bytes` object is not exactly 20 bytes. ``` -------------------------------- ### Handling Invalid Byte Length Errors Source: https://context7.com/svix/python-ksuid/llms.txt Catch `ByteArrayLengthException` when `Ksuid.from_bytes()` or `KsuidMs.from_bytes()` receive incorrect byte lengths (expected 20 bytes), or when the constructor is given a `payload` of the wrong size. ```python from ksuid import Ksuid, ByteArrayLengthException # Wrong number of bytes try: Ksuid.from_bytes(b'\de\ad\be\ef') except ByteArrayLengthException as e: print(e) # Incorrect value length 4 # Wrong payload length try: Ksuid(payload=b'\x00' * 5) # must be 16 bytes except ByteArrayLengthException as e: print(e) # Incorrect payload length 5 ``` -------------------------------- ### Accessing KSUID Payload Bytes Source: https://context7.com/svix/python-ksuid/llms.txt Retrieve the non-timestamp portion of a KSUID as bytes. For `Ksuid`, this is 16 bytes; for `KsuidMs`, it's 15 bytes. You can inject a known payload for deterministic IDs, useful in testing. ```python from ksuid import Ksuid import os # Inject a known payload for deterministic IDs (e.g., in tests) fixed_payload = bytes(range(16)) # 16 bytes: 0x00..0x0f k = Ksuid(payload=fixed_payload) assert k.payload == fixed_payload print(k.payload.hex()) # '000102030405060708090a0b0c0d0e0f' ``` -------------------------------- ### Deserialize Ksuid from raw bytes Source: https://context7.com/svix/python-ksuid/llms.txt Reconstructs a Ksuid from a 20-byte `bytes` object. Raises `ByteArrayLengthException` if the input is not exactly 20 bytes. ```python from ksuid import Ksuid, ByteArrayLengthException original = Ksuid() raw = bytes(original) # 20-byte bytes object restored = Ksuid.from_bytes(raw) assert restored == original print(f"Round-trip OK: {restored}") # '1sreAHoz6myPhXghsOdVBoec3Vr' # Error handling for invalid byte length try: Ksuid.from_bytes(b'\x00' * 10) except ByteArrayLengthException as e: print(f"Error: {e}") # Error: Incorrect value length 10 ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.