How to Generate Experiment Tracking Run IDs in Python

Generate unique experiment run IDs with timestamps and random suffixes for tracking ML pipeline executions.

Easy Python 3.9+ Aug 9, 2026 ML engineering pipelines 13 views 0 copies

Python code

14 lines
Python 3.9+
import random
import string
import time

def generate_run_id(prefix="exp"):
    timestamp = time.strftime("%Y%m%d_%H%M%S")
    suffix = "".join(random.choices(string.ascii_lowercase + string.digits, k=6))
    return f"{prefix}_{timestamp}_{suffix}"

if __name__ == "__main__":
    # Simulate tracking three experiment runs
    for i in range(3):
        run_id = generate_run_id()
        print(f"Run {i + 1}: {run_id}")

Output

stdout
Run 1: exp_20240315_143022_ab3x9z
Run 2: exp_20240315_143022_k7p2mq
Run 3: exp_20240315_143022_t5w8jr

How it works

The generate_run_id function combines a timestamp from time.strftime with a random 6-character alphanumeric suffix. This creates human-readable, chronologically sortable IDs unique enough for most experiment tracking needs. The timestamp ensures IDs are roughly ordered by creation time, while the random suffix reduces collision probability. Using random.choices with string.ascii_lowercase + string.digits avoids ambiguous characters and keeps IDs compact.

Common mistakes

  • Forgetting that two runs in the same second can collide without the random suffix
  • Using `time.time()` directly instead of `strftime` which produces ugly unreadable IDs
  • Not including a prefix to distinguish experiment types in large tracking systems

Variations

  1. Use `uuid.uuid4().hex[:6]` instead of `random.choices` for stronger uniqueness guarantees
  2. Format timestamp as `%Y%m%d%H%M%S%f` (with microseconds) to reduce collision risk further

Real-world use cases

  • Logging each training run into MLflow or Weights & Biases with a unique identifier for later comparison.
  • Storing model artifacts and checkpoints in cloud storage with run-specific keys for easy retrieval.
  • Tracking hyperparameter sweeps where each configuration needs a distinct ID to link results back.

Sponsored

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from ML engineering pipelines

Related tutorials and quizzes for this topic.