svix-ksuid

repository·main·Indexed 41 days ago

https://github.com/svix/python-ksuid

A pure-Python implementation of K-Sorted Unique Identifiers (KSUIDs) version 0.7.0. It provides identifiers with a timestamp component for chronological sorting, offering standard 1-second accuracy via Ksuid and higher precision (up to 4ms) via KsuidMs.

Tokens
836
Snippets
8
Records
8
Agent score
50%

What's inside svix-ksuid

  1. Compare and sort Ksuids

    main

    Ksuids are K-sorted, meaning they can be compared using standard Python comparison operators (<, <=, >, >=, ==). Comparison is based on the timestamp component, allowing you to sort them chronologically.

    from ksuid import Ksuid
    
    k1 = Ksuid()
    k2 = Ksuid()
    
    # Comparison works based on creation time
    print(k1 < k2)
    print(k1 == k2)
  2. Create a Ksuid from a datetime object

    main

    You can initialize a Ksuid with a specific datetime.datetime object.

    from datetime import datetime
    from ksuid import Ksuid
    
    dt = datetime(year=2021, month=5, day=19, hour=1, minute=1, second=1, microsecond=1)
    ksuid = Ksuid(dt)
    print(ksuid.datetime)
  3. Use higher timestamp accuracy mode with KsuidMs

    main

    Standard KSUIDs have 1-second accuracy. If your use case requires higher precision (up to 4ms), use KsuidMs.

    Note: KsuidMs is fully compatible with normal KSUIDs and outputs valid KSUID formats, but it sacrifices one byte of the random payload to provide the increased timestamp accuracy.

    from ksuid import KsuidMs
    
    ksuid = KsuidMs()
  4. Create a Ksuid from bytes

    main

    Use the .from_bytes() method on a Ksuid instance to reconstruct it from its raw byte representation.

    from ksuid import Ksuid
    
    ksuid = Ksuid()
    ksuid_from_bytes = ksuid.from_bytes(bytes(ksuid))
    print(ksuid == ksuid_from_bytes)  # True
  5. Access Ksuid properties (datetime, timestamp, payload)

    main

    Once a Ksuid object is created, you can access its constituent parts:

    • .datetime: The datetime.datetime object representing the creation time.
    • .timestamp: The integer Unix timestamp.
    • .payload: The raw bytes of the random payload.
    • String representation: The object returns its Base62 encoded string when cast to a string.
    from ksuid import Ksuid
    
    ksuid = Ksuid()
    print(f"Base62: {ksuid}")
    print(f"Bytes: {bytes(ksuid)}")
    print(f"Datetime: {ksuid.datetime}")
    print(f"Timestamp: {ksuid.timestamp}")
    print(f"Payload: {ksuid.payload}")
  6. Create a Ksuid from a Base62 string

    main

    Use the Ksuid.from_base62() class method to reconstruct a Ksuid from its Base62 string representation.

    from ksuid import Ksuid
    
    # Example Base62 string
    base62_str = "1srdszO8Xy2cR6CnARnvxCfRmK4"
    ksuid = Ksuid.from_base62(base62_str)
    print(ksuid.timestamp)