this string has no description
tid_timestamp.py
50 lines 1.6 kB view raw
1#!/usr/bin/env python3 2"""Extract timestamp values from AT Protocol TID strings.""" 3 4import datetime 5 6# Base32-sortable alphabet used by TIDs 7BASE32_SORTABLE = "234567abcdefghijklmnopqrstuvwxyz" 8 9 10def tid_to_timestamp(tid: str) -> int: 11 """Convert a TID string to microseconds since UNIX epoch.""" 12 if len(tid) != 13: 13 raise ValueError(f"TID must be 13 characters, got {len(tid)}") 14 15 # Decode base32-sortable to integer 16 value = 0 17 for char in tid: 18 idx = BASE32_SORTABLE.find(char) 19 if idx == -1: 20 raise ValueError(f"Invalid character in TID: {char!r}") 21 value = value * 32 + idx 22 23 # Extract timestamp (top 54 bits, but bit 63 is always 0, so really 53 bits) 24 # The bottom 10 bits are the clock identifier 25 timestamp_us = value >> 10 26 27 return timestamp_us 28 29 30def tid_to_datetime(tid: str) -> datetime.datetime: 31 """Convert a TID string to a datetime object (UTC).""" 32 timestamp_us = tid_to_timestamp(tid) 33 return datetime.datetime.fromtimestamp(timestamp_us / 1_000_000, tz=datetime.timezone.utc) 34 35 36if __name__ == "__main__": 37 import sys 38 39 if len(sys.argv) < 2: 40 print(f"Usage: {sys.argv[0]} <tid> [tid ...]") 41 print(f"Example: {sys.argv[0]} 3jzfcijpj2z2a") 42 sys.exit(1) 43 44 for tid in sys.argv[1:]: 45 try: 46 ts_us = tid_to_timestamp(tid) 47 dt = tid_to_datetime(tid) 48 print(f"{tid} -> {ts_us} µs -> {dt.isoformat()}") 49 except ValueError as e: 50 print(f"{tid} -> Error: {e}", file=sys.stderr)