geekcomputers/Python · warning · ValueError

Time out of range

Error message

Time out of range

What it means

This ValueError is raised by the Tkinter calculate callback after the HH:MM:SS shape check passes but the parsed components are out of calendar range: hours must satisfy 0 <= h < 24, minutes 0 <= m < 60, seconds 0 <= s < 60. It catches semantically impossible times like 25:00:00 or 12:61:00 that are shape-valid but not real clock times, and is displayed to the user via messagebox.showerror.

Source

Thrown at Timetable_Operations.py:45

    if diff < 0:
        diff += 24 * 3600
    h = diff // 3600
    m = (diff % 3600) // 60
    s = diff % 60
    return f"{h:02}:{m:02}:{s:02}"


def calculate() -> None:
    """Tkinter callback to calculate and display clock difference."""
    t1 = entry_t1.get().strip()
    t2 = entry_t2.get().strip()
    try:
        for t in [t1, t2]:
            if len(t) != 8 or t[2] != ":" or t[5] != ":":
                raise ValueError("Format must be HH:MM:SS")
            h, m, s = int(t[0:2]), int(t[3:5]), int(t[6:8])
            if not (0 <= h < 24 and 0 <= m < 60 and 0 <= s < 60):
                raise ValueError("Time out of range")
        result = clock_diff(t1, t2)
        label_result.config(text=f"Difference: {result}")
    except Exception as e:
        messagebox.showerror("Error", f"Invalid input!\n{e}")


root = tk.Tk()
root.title("Clock Difference Calculator")
root.geometry("300x200")

tk.Label(root, text="Init schedule (HH:MM:SS):").pack(pady=5)
entry_t1 = tk.Entry(root)
entry_t1.pack()

tk.Label(root, text="Final schedule (HH:MM:SS):").pack(pady=5)
entry_t2 = tk.Entry(root)
entry_t2.pack()

View on GitHub (pinned to 40f4cd2652)

Solutions

  1. Enter valid times: hours 00-23, minutes 00-59, seconds 00-59; use 00:00:00 for midnight
  2. If computing times programmatically, normalize with divmod carry (s//60 etc.) or datetime arithmetic before display
  3. Add a dropdown/spinbox constrained to valid ranges instead of free text

Example fix

# before
# user enters 24:15:30 -> error

# after
from datetime import datetime, timedelta
t = (datetime(2000,1,1) + timedelta(hours=24, minutes=15)).strftime('%H:%M:%S')  # '00:15:00'
Defensive patterns

Strategy: validation

Validate before calling

def valid_time(t):
    h, m, s = int(t[0:2]), int(t[3:5]), int(t[6:8])
    return 0 <= h < 24 and 0 <= m < 60 and 0 <= s < 60
if valid_time(t1) and valid_time(t2):
    calculate()

Type guard

def is_valid_clock_time(t: str) -> bool:
    import re
    if not re.fullmatch(r'\d{2}:\d{2}:\d{2}', t):
        return False
    h, m, s = map(int, t.split(':'))
    return 0 <= h < 24 and 0 <= m < 60 and 0 <= s < 60

Try / catch

try:
    calculate()
except ValueError as e:
    messagebox.showerror('Out of range', str(e))

Prevention

When it happens

Trigger: Entering '24:00:00' (24 is rejected; use 00:00:00), '12:75:00', '09:30:99', or any well-formatted string whose component exceeds its bound. Note the int() parse of e.g. '0x' would raise a different ValueError caught by the same handler.

Common situations: Users entering 24 for midnight, typos in minutes/seconds, or times computed programmatically (e.g., adding durations) that overflow component bounds without carry normalization.

Understand the failure class

Related errors


AI-assisted analysis of geekcomputers/Python@40f4cd2652 (2026-08-27). Data as JSON: /api/errors/bff4d9d872ab1f1a. Report an issue: GitHub.