To solve this problem, we need to create a function that converts a time string in the format "HH:MM:SS" into the total number of seconds, while handling various invalid input cases.
Approach
The approach to solve this problem involves the following steps:
- Input Validation: Check if the input string is in the correct format (exactly two colons separating three parts: hours, minutes, seconds).
- Type Conversion: Convert each part of the time string to an integer.
- Range Check: Ensure that hours are non-negative, and minutes/seconds are within the valid range (0 to 59 inclusive).
- Calculation: Compute the total number of seconds using the formula:
hours * 3600 + minutes * 60 + seconds. - Error Handling: Raise descriptive ValueError exceptions for invalid inputs to inform the caller about the specific issue.
Solution Code
def convert_to_seconds(time_str):
"""
Converts a time string in "HH:MM:SS" format to the total number of seconds.
Args:
time_str (str): Time string in "HH:MM:SS" format.
Returns:
int: Total number of seconds.
Raises:
ValueError: If the input string is not in the correct format,
if any part is not an integer,
if hours are negative,
or if minutes/seconds are outside the range [0, 59].
"""
try:
# Split the time string into hours, minutes, seconds parts
parts = time_str.split(':')
if len(parts) != 3:
raise ValueError("Invalid format: Expected 'HH:MM:SS' (exactly two colons).")
# Convert parts to integers
hours = int(parts[0])
minutes = int(parts[1])
seconds = int(parts[2])
# Validate ranges
if hours < 0:
raise ValueError(f"Invalid hours: {hours} (must be non-negative).")
if not (0 <= minutes < 60):
raise ValueError(f"Invalid minutes: {minutes} (must be between 0 and 59).")
if not (0 <= seconds < 60):
raise ValueError(f"Invalid seconds: {seconds} (must be between 0 and 59).")
# Calculate total seconds
total_seconds = hours * 3600 + minutes * 60 + seconds
return total_seconds
except ValueError as e:
# Re-raise the error with a clear message
raise ValueError(f"Failed to convert time: {str(e)}") from None
Explanation
- Input Validation: The function first splits the input string using colons. If the split results in fewer or more than three parts, it raises an error.
- Type Conversion: Each part is converted to an integer. If any part cannot be converted (e.g., non-numeric characters), a ValueError is raised.
- Range Check: The function checks if hours are non-negative and if minutes/seconds are within the valid range (0-59). If not, it raises an error with a specific message.
- Calculation: The total seconds are computed by converting hours to seconds (multiply by 3600), minutes to seconds (multiply by 60), and adding the seconds part.
- Error Handling: All exceptions are caught and re-raised with a descriptive message to help the caller understand the issue.
This approach ensures that the function is robust and handles all possible invalid inputs gracefully. It provides clear feedback to the user about what went wrong, making it easier to correct the input.


作者声明:本文包含人工智能生成内容。