HexDate

This is my Python script HexDate – it will encode/decode the date-time as a hex code, based on the coding system:

“bin”: Base 2
“oct”: Base 8
“dec”: Base 10
“hex”: Base 16 (UPPER)
“b32”: Base 32 (RFC 4648 Upper)
“b36”: Base 36 (UPPER)
“b26”: Base 26 (A..Z)

 
#!/usr/bin/env python3
"""
HexDate — numeric base conversion of a date/time (yymmddhhmm).

This tool takes a local time formatted as yymmddhhmm, interprets it as a
NON-NEGATIVE INTEGER, and renders it in the selected base, OR decodes a base-encoded
string back into a formatted date/time string.

Usage:
  HexDate [-b BASE] [INPUT] [FORMAT]
  HexDate --list
  HexDate -h | --help

Options:
  -b, --base BASE  Select output/input base (default: hex).
  --list           Print the supported bases and exit.
  -h, --help       Show this help message.

Arguments:
  INPUT            Optional. Either a date-time string (YYMMDDHHMM) to encode,
                   or an encoded string to decode back to a date.
  FORMAT           Optional bash-style date format (e.g., "+%Y-%m-%d %H:%M")
                   used only when decoding.
"""

import sys
import argparse
from datetime import datetime

# Uppercase-only alphabets for numeric conversion [cite: 8]
ALPHABETS = {
    "bin": "01",                                          # Base2 [cite: 8, 9]
    "oct": "01234567",                                    # Base8 [cite: 9]
    "dec": "0123456789",                                  # Base10 [cite: 9, 10]
    "hex": "0123456789ABCDEF",                            # Base16 (UPPER) [cite: 10]
    "b32": "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",            # Base32 (RFC 4648 UPPER) [cite: 10]
    "b36": "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ",         # Base36 (UPPER) [cite: 10]
    "b26": "ABCDEFGHIJKLMNOPQRSTUVWXYZ",                  # Base26 (A=0..Z=25) [cite: 10, 11]
}

def to_base(n: int, alphabet: str) -> str:
    """Convert non-negative integer n to a string in the given alphabet.""" [cite: 11]
    if n < 0: raise ValueError("Negative values are not supported.") [cite: 11] if n == 0: return alphabet[0] [cite: 11] base = len(alphabet) [cite: 11] out = [] [cite: 11] while n: n, r = divmod(n, base) [cite: 11] out.append(alphabet[r]) [cite: 12] return "".join(reversed(out)) [cite: 12] def from_base(s: str, alphabet: str) -> int:
    """Convert a string in the given alphabet back to a non-negative integer."""
    base = len(alphabet)
    n = 0
    for char in s:
        if char not in alphabet:
            sys.exit(f"Error: Character '{char}' is not in the alphabet for this base.")
        n = n * base + alphabet.index(char)
    return n

def format_bash_date(dt_str: str, bash_fmt: str) -> str:
    """Convert bash 'date' format tokens into python strftime tokens."""
    # Remove leading '+' if present
    if bash_fmt.startswith('+'):
        bash_fmt = bash_fmt[1:]

    try:
        dt = datetime.strptime(dt_str, "%y%m%d%H%M")
    except ValueError:
        sys.exit(f"Error: Decoded integer '{dt_str}' does not map to a valid YYMMDDHHMM timestamp.")

    # Python strftime shares most common tokens with bash date (%Y, %m, %d, %H, %M, %S, etc.)
    return dt.strftime(bash_fmt)

def print_list():
    print("Supported bases:") [cite: 12]
    for key in ("bin", "oct", "dec", "hex", "b32", "b36", "b26"): [cite: 12]
        print(f"  {key:<4} (base {len(ALPHABETS[key])})") [cite: 12] def main(): # We use parse_known_args because bash format tokens like '+%Y' look like flags to argparse parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter, add_help=False) parser.add_argument("-b", "--base", default="hex", help="Select output base.") parser.add_argument("--list", action="store_true", help="Print supported bases and exit.") parser.add_argument("-h", "--help", action="store_true", help="Show help.") args, remaining = parser.parse_known_args() if args.help: print(__doc__) return if args.list: print_list() return base_name = args.base.lower() if base_name not in ALPHABETS: sys.exit(f"Unknown base: {base_name}\nUse --list to see supported options.") alphabet = ALPHABETS[base_name] # Separate positional arguments from potential bash format strings input_val = None date_format = None for item in remaining: if item.startswith('+'): date_format = item elif input_val is None: input_val = item else: # If a second non-format argument is passed, treat it as the format string without a '+' date_format = item # CASE 1: No date or encoded string provided -> Encode current time
    if input_val is None:
        stamp = datetime.now().strftime("%y%m%d%H%M")
        print(to_base(int(stamp), alphabet))
        return

    # CASE 2: Input is an explicit unencoded date-time string (digits only, 10 characters)
    if input_val.isdigit() and len(input_val) == 10:
        print(to_base(int(input_val), alphabet))
        return

    # CASE 3: Input is an encoded custom-base string -> Decode back to date-time
    decoded_int = from_base(input_val.upper(), alphabet)
    decoded_str = str(decoded_int)

    # Pad left with zeroes if the timestamp dropped leading zeroes (e.g., early morning or early year digits)
    if len(decoded_str) < 10:
        decoded_str = decoded_str.zfill(10)

    # Output formatting
    if date_format:
        print(format_bash_date(decoded_str, date_format))
    else:
        # Default fallback format matches bash date output default style, e.g. "YY-MM-DD HH:MM"
        print(format_bash_date(decoded_str, "+%Y-%m-%d %H:%M"))

if __name__ == "__main__":
    main()


How to use it

1. Current time conversion (Original functionality):

BASH

$ ./HexDate
95A0F7E

2. Convert a specific date-time: Provide a 10-digit standard timestamp (YYMMDDHHMM.

BASH
$ ./HexDate 2605231830
9B24FE6

3. Convert an encoded value back to a date (with default formatting): If the argument doesn’t match the 10-digit structure, the script will decode it based on your selected base.

BASH

$ ./HexDate 9B24FE6
2026-05-23 18:30

4. Convert back to a date using Bash date formatting styles: Append your format string starting with a +token.

BASH

$ ./HexDate 9B24FE6 "+%A, %d %B %Y at %I:%M %p"
Saturday, 23 May 2026 at 06:30 PM

$ ./HexDate -b b36 1H2N28 "+%d/%m/%y"
23/05/26