|
| 1 | +""" |
| 2 | +A unit of time is any particular time interval, used as a standard |
| 3 | +way of measuring or expressing duration. |
| 4 | +The base unit of time in the International System of Units (SI), |
| 5 | +and by extension most of the Western world, is the second, |
| 6 | +defined as about 9 billion oscillations of the caesium atom. |
| 7 | +
|
| 8 | +WIKI: https://en.wikipedia.org/wiki/Unit_of_time |
| 9 | +""" |
| 10 | + |
| 11 | +time_chart: dict[str, float] = { |
| 12 | + "seconds": 1.0, |
| 13 | + "minutes": 60.0, # 1 minute = 60 sec |
| 14 | + "hours": 3600.0, # 1 hour = 60 minutes = 3600 seconds |
| 15 | + "days": 86400.0, # 1 day = 24 hours = 1440 min = 86400 sec |
| 16 | + "weeks": 604800.0, # 1 week=7d=168hr=10080min = 604800 sec |
| 17 | +} |
| 18 | + |
| 19 | +time_chart_inverse: dict[str, float] = { |
| 20 | + "seconds": 1.0, |
| 21 | + "minutes": 1 / 60.0, # 1 minute = 1/60 hours |
| 22 | + "hours": 1 / 3600.0, # 1 hour = 1/3600 days |
| 23 | + "days": 1 / 86400.0, # 1 day = 1/86400 weeks |
| 24 | + "weeks": 1 / 604800.0, # 1 week = 1/604800 seconds |
| 25 | +} |
| 26 | + |
| 27 | +def convert_time(time_value: float, unit_from: str, unit_to: str) -> float: |
| 28 | + """ |
| 29 | + Convert time from one unit to another using the time_chart above. |
| 30 | +
|
| 31 | + >>> convert_time(3600, "seconds", "hours") |
| 32 | + 1.0 |
| 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 | + """ |
| 42 | + if unit_to not in time_chart or unit_from not in time_chart_inverse: |
| 43 | + msg = ( |
| 44 | + f"Incorrect 'from_type' or 'to_type' value: {unit_from!r}, {unit_to!r}\n" |
| 45 | + f"Valid values are: {', '.join(time_chart_inverse)}" |
| 46 | + ) |
| 47 | + raise ValueError(msg) |
| 48 | + return round(time_value * time_chart[unit_from] * time_chart_inverse[unit_to], 3) |
| 49 | + |
| 50 | +if __name__ == "__main__": |
| 51 | + import doctest |
| 52 | + doctest.testmod() |
| 53 | + |
| 54 | + print(convert_time(3600, "seconds", "hours")) |
0 commit comments