python/cpython · error · ValueError

fold must be either 0 or 1, not {fold}

Error message

fold must be either 0 or 1, not {fold}

What it means

Raised by _check_time_fields() when the fold argument to time()/datetime() is not exactly 0 or 1. fold is PEP 495's disambiguator for repeated wall times during DST fold-back; it is a strict two-valued flag, not a boolean-coerced or arbitrary integer field.

Source

Thrown at Lib/_pydatetime.py:595

    if not 1 <= day <= dim:
        raise ValueError(f"day {day} must be in range 1..{dim} for month {month} in year {year}")
    return year, month, day

def _check_time_fields(hour, minute, second, microsecond, fold):
    hour = _index(hour)
    minute = _index(minute)
    second = _index(second)
    microsecond = _index(microsecond)
    if not 0 <= hour <= 23:
        raise ValueError(f"hour must be in 0..23, not {hour}")
    if not 0 <= minute <= 59:
        raise ValueError(f"minute must be in 0..59, not {minute}")
    if not 0 <= second <= 59:
        raise ValueError(f"second must be in 0..59, not {second}")
    if not 0 <= microsecond <= 999999:
        raise ValueError(f"microsecond must be in 0..999999, not {microsecond}")
    if fold not in (0, 1):
        raise ValueError(f"fold must be either 0 or 1, not {fold}")
    return hour, minute, second, microsecond, fold

def _check_tzinfo_arg(tz):
    if tz is not None and not isinstance(tz, tzinfo):
        raise TypeError(
            "tzinfo argument must be None or of a tzinfo subclass, "
            f"not {type(tz).__name__!r}"
        )

def _divide_and_round(a, b):
    """divide a by b and round result to the nearest integer

    When the ratio is exactly half-way between two integers,
    the even integer is returned.
    """
    # Based on the reference implementation for divmod_near
    # in Objects/longobject.c.
    q, r = divmod(a, b)

View on GitHub (pinned to bc6749cc3b)

Solutions

  1. Pass only literal 0 or 1 (or a bool) as fold
  2. Normalize on ingest: fold = 1 if fold in ('1', 1, True) else 0
  3. Keep fold out of arithmetic; treat it as a flag you copy verbatim

Example fix

// before
t = time(1, 30, fold=int(fold_str) * 2)  # can produce 2
// after
t = time(1, 30, fold=1 if fold_str == '1' else 0)
Defensive patterns

Strategy: validation

Validate before calling

fold = 1 if fold in (1, True, '1') else 0
t = time(h, m, s, us, fold=fold)

Type guard

def valid_fold(f) -> bool:
    return f in (0, 1)

Prevention

When it happens

Trigger: time(1, 30, fold=2); datetime(..., fold=True) works (bool is int 1) but fold=2 fails; passing a fold computed from arithmetic like fold_a + fold_b.

Common situations: Serializing/deserializing fold from JSON where it arrives as 0/1 strings or other ints; copying fold between objects with arithmetic; confusing fold with an hour-offset count.

Related errors


AI-assisted analysis of python/cpython@bc6749cc3b (2026-08-14). Data as JSON: /api/errors/4053ac780930017a. Report an issue: GitHub.