Convert time from one unit to another using the time_chart above. >>> convert_time(3600, "seconds", "hours") 1.0 >>> convert_time(3500, "Seconds", "Hours") 0.972 >>> convert_time(1, "DaYs", "hours") 24.0 >>> convert_time(120, "minutes", "SeCoNdS") 7200.0 >>>
(time_value: float, unit_from: str, unit_to: str)
| 23 | |
| 24 | |
| 25 | def convert_time(time_value: float, unit_from: str, unit_to: str) -> float: |
| 26 | """ |
| 27 | Convert time from one unit to another using the time_chart above. |
| 28 | |
| 29 | >>> convert_time(3600, "seconds", "hours") |
| 30 | 1.0 |
| 31 | >>> convert_time(3500, "Seconds", "Hours") |
| 32 | 0.972 |
| 33 | >>> convert_time(1, "DaYs", "hours") |
| 34 | 24.0 |
| 35 | >>> convert_time(120, "minutes", "SeCoNdS") |
| 36 | 7200.0 |
| 37 | >>> convert_time(2, "WEEKS", "days") |
| 38 | 14.0 |
| 39 | >>> convert_time(0.5, "hours", "MINUTES") |
| 40 | 30.0 |
| 41 | >>> convert_time(-3600, "seconds", "hours") |
| 42 | Traceback (most recent call last): |
| 43 | ... |
| 44 | ValueError: 'time_value' must be a non-negative number. |
| 45 | >>> convert_time("Hello", "hours", "minutes") |
| 46 | Traceback (most recent call last): |
| 47 | ... |
| 48 | ValueError: 'time_value' must be a non-negative number. |
| 49 | >>> convert_time([0, 1, 2], "weeks", "days") |
| 50 | Traceback (most recent call last): |
| 51 | ... |
| 52 | ValueError: 'time_value' must be a non-negative number. |
| 53 | >>> convert_time(1, "cool", "century") # doctest: +ELLIPSIS |
| 54 | Traceback (most recent call last): |
| 55 | ... |
| 56 | ValueError: Invalid unit cool is not in seconds, minutes, hours, days, weeks, ... |
| 57 | >>> convert_time(1, "seconds", "hot") # doctest: +ELLIPSIS |
| 58 | Traceback (most recent call last): |
| 59 | ... |
| 60 | ValueError: Invalid unit hot is not in seconds, minutes, hours, days, weeks, ... |
| 61 | """ |
| 62 | if not isinstance(time_value, (int, float)) or time_value < 0: |
| 63 | msg = "'time_value' must be a non-negative number." |
| 64 | raise ValueError(msg) |
| 65 | |
| 66 | unit_from = unit_from.lower() |
| 67 | unit_to = unit_to.lower() |
| 68 | if unit_from not in time_chart or unit_to not in time_chart: |
| 69 | invalid_unit = unit_from if unit_from not in time_chart else unit_to |
| 70 | msg = f"Invalid unit {invalid_unit} is not in {', '.join(time_chart)}." |
| 71 | raise ValueError(msg) |
| 72 | |
| 73 | return round( |
| 74 | time_value * time_chart[unit_from] * time_chart_inverse[unit_to], |
| 75 | 3, |
| 76 | ) |
| 77 | |
| 78 | |
| 79 | if __name__ == "__main__": |