Skip to content

Commit f66e67b

Browse files
author
Jeel Gajera
committed
Add: Time Conversion Function
1 parent 0601b56 commit f66e67b

File tree

2 files changed

+55
-0
lines changed

2 files changed

+55
-0
lines changed

Diff for: DIRECTORY.md

+1
Original file line numberDiff line numberDiff line change
@@ -174,6 +174,7 @@
174174
* [Roman Numerals](conversions/roman_numerals.py)
175175
* [Speed Conversions](conversions/speed_conversions.py)
176176
* [Temperature Conversions](conversions/temperature_conversions.py)
177+
* [Time Conversions](conversions/time_conversions.py)
177178
* [Volume Conversions](conversions/volume_conversions.py)
178179
* [Weight Conversion](conversions/weight_conversion.py)
179180

Diff for: conversions/time_conversions.py

+54
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
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

Comments
 (0)