Skip to content

Commit dafa3bb

Browse files
authored
Merge pull request #180 from Sockney89/main
feat: Duration Calculator in Python
2 parents e8dff09 + 97cc408 commit dafa3bb

File tree

3 files changed

+144
-1
lines changed

3 files changed

+144
-1
lines changed
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
# Duration Converter (Python)
2+
3+
A small Python command line utility for converting durations between a set of time units.
4+
5+
## Quick start
6+
7+
### Single conversion (one-shot)
8+
>
9+
> Run from project root:
10+
>```powershell
11+
>python main.py --value=3600 --source_unit=seconds --target_unit=hours
12+
>```
13+
14+
### Interactive mode
15+
>
16+
> Run from project root:
17+
>```powershell
18+
>python main.py
19+
>```
20+
>An interactive loop will start prompting for input value and source and target formats.
21+
22+
23+
## Supported units
24+
_Units need to be exactly as below:_
25+
- seconds
26+
- minutes
27+
- hours
28+
- days
29+
30+
## Requirements
31+
- Python 3.x installed on your system.
Lines changed: 111 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,111 @@
1+
import argparse
2+
3+
class DurationCalculator:
4+
"""A class to convert durations between different time units."""
5+
6+
def __init__(self,interactive=True,arguments=None):
7+
8+
# Define time Units and their values in seconds
9+
self.time_units = {
10+
'seconds': 1,
11+
'minutes': 60,
12+
'hours': 3600,
13+
'days': 86400
14+
}
15+
16+
if interactive:
17+
self.run_interactive_mode()
18+
else:
19+
converted_value = self.convert_duration(arguments['value'], arguments['source_unit'], arguments['target_unit'])
20+
print(f"{arguments['value']} {arguments['source_unit']} is equal to {converted_value} {arguments['target_unit']}.")
21+
22+
def convert_duration(self, value:int, source_unit:str, target_unit:str) -> float:
23+
"""Convert duration from source unit to target unit"""
24+
25+
# Sanity check on units
26+
if source_unit not in self.time_units:
27+
raise ValueError(f"Unsupported source unit: {source_unit}")
28+
if target_unit not in self.time_units:
29+
raise ValueError(f"Unsupported target unit: {target_unit}")
30+
31+
# Sanity check; value must be non-negative
32+
if value < 0:
33+
raise ValueError("Duration value must be non-negative")
34+
35+
# Convert value in source unit to seconds
36+
value_in_seconds = value * self.time_units[source_unit]
37+
38+
# Convert seconds to duration in target unit
39+
converted_value = value_in_seconds / self.time_units[target_unit]
40+
41+
return converted_value
42+
43+
44+
def run_interactive_mode(self):
45+
"""Run the interactive mode for user input"""
46+
47+
self.print_greeting()
48+
self.print_interactive_help()
49+
50+
try:
51+
exit_flag = False
52+
while not exit_flag:
53+
user_choice = input("Type 'r' to run conversion or 'q' to exit. \n").strip().lower()
54+
if user_choice == 'r':
55+
self.handle_conversion()
56+
elif user_choice == 'q':
57+
print("Exiting interactive mode. Goodbye!")
58+
exit_flag = True
59+
else:
60+
print("Invalid choice. Please type 'r' or 'q'.")
61+
except KeyboardInterrupt:
62+
print("\nExiting interactive mode. Goodbye!")
63+
64+
def handle_conversion(self):
65+
"""Handle a single conversion interaction with the user"""
66+
67+
try:
68+
value = float(input("Enter the duration value to convert: ").strip())
69+
source_unit = input("Enter the source unit (seconds, minutes, hours, days): ").strip().lower()
70+
target_unit = input("Enter the target unit (seconds, minutes, hours, days): ").strip().lower()
71+
72+
converted_value = self.convert_duration(value, source_unit, target_unit)
73+
print(f"{value} {source_unit} is equal to {converted_value} {target_unit}.")
74+
75+
except ValueError as e:
76+
print(f"Error during conversion: {e}")
77+
78+
def print_greeting(self):
79+
"""Print a decorated greeting message"""
80+
81+
print("************************************")
82+
print(" Welcome to the Duration Converter ")
83+
print("************************************")
84+
85+
def print_interactive_help(self):
86+
"""Print help message for interactive mode"""
87+
88+
print("This tool converts durations between seconds, minutes, hours, and days.")
89+
print("You will be prompted to enter a duration value, source unit, and target unit.")
90+
91+
92+
93+
if __name__ == "__main__":
94+
# Get arguments from command line
95+
parser = argparse.ArgumentParser(description="Duration Converter Tool")
96+
parser.add_argument('--value', type=float, help="Duration value to convert")
97+
parser.add_argument('--source_unit', type=str, help="Source time unit (seconds, minutes, hours, days)")
98+
parser.add_argument('--target_unit', type=str, help="Target time unit (seconds, minutes, hours, days)")
99+
args = parser.parse_args()
100+
101+
# Determine mode based on provided arguments
102+
if args.value is not None and args.source_unit and args.target_unit:
103+
arguments = {
104+
'value': args.value,
105+
'source_unit': args.source_unit,
106+
'target_unit': args.target_unit
107+
}
108+
DurationCalculator(interactive=False, arguments=arguments)
109+
else:
110+
DurationCalculator(interactive=True)
111+

README.md

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -48,7 +48,7 @@ If you like this initiative, **give it a ⭐** and help make this the ultimate o
4848

4949
## 🧰 Current Calculators
5050

51-
Current Unique Contributor Amount is **42**!
51+
Current Unique Contributor Amount is **43**!
5252

5353

5454
| Calculator Name | Programming Language | Contributors |
@@ -88,6 +88,7 @@ Current Unique Contributor Amount is **42**!
8888
| `DurationConverter-Java-rohithgowda18` | Java | [@rohithgowda18](https://github.com/rohithgowda18) |
8989
| `DurationConverter-C++-abdllahmaher` | C++ | [@abdllahmaher](https://github.com/abdllahmaher) |
9090
| `DurationConverter-Python-JuanManuel` | Python | [@MAXXIMUX12](https://github.com/MAXXIMUX12) |
91+
| `DurationConverter-Python-Sockney89` | Python | [@Sockney89](https://github.com/Sockney89)|
9192
| `DataStorageConverter-Python-ifauzeee` | Python | [@ifauzeee](https://github.com/ifauzeee) |
9293
| `DataStorageConverter-Python-jaideepkathiresan` | Python | [@jaideepkathiresan](https://github.com/jaideepkathiresan) |
9394
| `DataStorageConverter-Java-umer901` | Java | [@umer901](https://github.com/umer901) |

0 commit comments

Comments
 (0)