{"record":{"id":"54839dc32c4a1b8c","repo":"TheAlgorithms/Python","slug":"time-value-must-be-a-non-negative-number","errorCode":null,"errorMessage":"'time_value' must be a non-negative number.","messagePattern":"'time_value' must be a non-negative number\\.","errorType":"exception","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"conversions/time_conversions.py","lineNumber":64,"sourceCode":"    Traceback (most recent call last):\n        ...\n    ValueError: 'time_value' must be a non-negative number.\n    >>> convert_time([0, 1, 2], \"weeks\", \"days\")\n    Traceback (most recent call last):\n        ...\n    ValueError: 'time_value' must be a non-negative number.\n    >>> convert_time(1, \"cool\", \"century\")  # doctest: +ELLIPSIS\n    Traceback (most recent call last):\n        ...\n    ValueError: Invalid unit cool is not in seconds, minutes, hours, days, weeks, ...\n    >>> convert_time(1, \"seconds\", \"hot\")  # doctest: +ELLIPSIS\n    Traceback (most recent call last):\n        ...\n    ValueError: Invalid unit hot is not in seconds, minutes, hours, days, weeks, ...\n    \"\"\"\n    if not isinstance(time_value, (int, float)) or time_value < 0:\n        msg = \"'time_value' must be a non-negative number.\"\n        raise ValueError(msg)\n\n    unit_from = unit_from.lower()\n    unit_to = unit_to.lower()\n    if unit_from not in time_chart or unit_to not in time_chart:\n        invalid_unit = unit_from if unit_from not in time_chart else unit_to\n        msg = f\"Invalid unit {invalid_unit} is not in {', '.join(time_chart)}.\"\n        raise ValueError(msg)\n\n    return round(\n        time_value * time_chart[unit_from] * time_chart_inverse[unit_to],\n        3,\n    )\n\n\nif __name__ == \"__main__\":\n    import doctest\n\n    doctest.testmod()","sourceCodeStart":46,"sourceCodeEnd":82,"githubUrl":"https://github.com/TheAlgorithms/Python/blob/f5988cc09713315817df6a7e327e258013a94440/conversions/time_conversions.py#L46-L82","documentation":"Raised by convert_time() in conversions/time_conversions.py when time_value is not an int/float or is negative. Note the isinstance check accepts bool (subclass of int) and rejects numeric strings like '60'. Units are validated separately in a later check.","triggerScenarios":"Calling convert_time(-1, 'seconds', 'minutes'), convert_time('60', 'seconds', 'minutes') (string), or passing None from an optional field.","commonSituations":"Timestamps/deltas computed as date differences that went negative due to ordering; CLI/query params arriving as strings and not cast; NaN from empty pandas cells (float NaN passes isinstance but NaN < 0 is False — NaN slips through, so sanitize it yourself).","solutions":["Cast numeric strings: convert_time(float(user_input), ...).","Use abs() or validate ordering if negative deltas are computation-order artifacts.","Reject NaN explicitly: if math.isnan(v): raise before calling."],"exampleFix":"# before\nconvert_time('-60', 'seconds', 'minutes')  # ValueError: 'time_value' must be a non-negative number.\n\n# after\nvalue = float('-60')\nif value < 0:\n    raise ValueError('duration cannot be negative')\nconvert_time(value, 'seconds', 'minutes')","handlingStrategy":"validation","validationCode":"import math\n\nif not isinstance(time_value, (int, float)) or isinstance(time_value, bool):\n    time_value = float(time_value)\nif math.isnan(time_value) or time_value < 0:\n    raise ValueError('duration must be a non-negative number')\nconvert_time(time_value, unit_from, unit_to)","typeGuard":"def is_valid_duration(v: object) -> bool:\n    return (\n        isinstance(v, (int, float))\n        and not isinstance(v, bool)\n        and not (isinstance(v, float) and math.isnan(v))\n        and v >= 0\n    )","tryCatchPattern":"try:\n    convert_time(v, f, t)\nexcept ValueError as e:\n    if 'non-negative' in str(e):\n        v = abs(float(v))\n        result = convert_time(v, f, t)\n    else:\n        raise","preventionTips":["Cast string params to float before calling","Reject NaN from empty data cells explicitly","Validate end > start when computing deltas"],"tags":["python","validation","units","time","conversion"],"backgroundTag":null,"analyzedSha":"f5988cc09713315817df6a7e327e258013a94440","analyzedAt":"2026-08-14T17:30:07.041Z","schemaVersion":2},"datasetVersion":"2026-08-15T22:17:37.221Z"}