Create a Time Class in Python Supporting Addition and Subtraction
We will create a class named Time class that can represent a time (hours, minutes, seconds) and supports time addition and subtraction. We will implement the __add__ and __sub__ method to support time addition and subtraction.
Example
class
Time:
def
init
(
self
,
hours
,
minutes
,
seconds
)
:
self
.
hours
=
hours
self
.
minutes
=
minutes
self
.
seconds
=
seconds
self
.
normalize
(
)
def
normalize
(
self
)
:
extra_minutes
,
self
.
seconds
=
divmod
(
self
.
seconds
,
60
)
self
.
minutes
=
extra_minutes
extra_hours
,
self
.
minutes
=
divmod
(
self
.
minutes
,
60
)
self
.
hours
=
extra_hours
def
add
(
self
,
other
)
:
total_seconds
=
self
.
hours
3600
self
.
minutes
60
self
.
seconds
total_seconds +
=
other.
hours
3600
- other.
minutes
60
- other.
seconds
hours
,
remainder
=
divmod
(
total_seconds
,
3600
)
minutes
,
seconds
=
divmod
(
remainder
,
60
)
return
Time
(
hours
,
minutes
,
seconds
)
def
sub
(
self
,
other
)
:
total_seconds
=
self
.
hours
3600
self
.
minutes
60
self
.
seconds
total_seconds -
=
other.
hours
3600
- other.
minutes
60
- other.
seconds
hours
,
remainder
=
divmod
(
total_seconds
,
3600
)
minutes
,
seconds
=
divmod
(
remainder
,
60
)
return
Time
(
hours
,
minutes
,
seconds
)
def
str
(
self
)
:
return
f
"{self.hours:02}:{self.minutes:02}:{self.seconds:02}"
Example usage
time1
=
Time
(
2
,
30
,
45
)
time2
=
Time
(
1
,
15
,
20
)
(
"Time 1:"
,
time1
)
(
"Time 2:"
,
time2
)
time_sum
=
time1 + time2
(
"Time 1 + Time 2:"
,
time_sum
)
time_diff
=
time1 - time2
(
"Time 1 - Time 2:"
,
time_diff
)
Code analysis:
__init__method: initializes theTimeAn instance of the class takes hours, minutes and seconds as parameters and calls thenormalizemethod to make sure the time format is correct.normalizemethod: convert seconds and minutes into a standard format, ensuring seconds do not exceed 59 and minutes do not exceed 59.__add__method: implement the addition of twoTimeobjects, converting the times to seconds, adding them, and converting back to hours, minutes and seconds.__sub__method: implement the addition of twoTimeThe subtraction of objects converts the times to seconds, subtracts them, and converts back to hours, minutes and seconds.__str__method: return a formatted time string, ensuring hours, minutes and seconds are all two digits.
Output result:
Time 1: 02:30:45
Time 2: 01:15:20
Time 1 + Time 2: 03:46:05
Time 1 - Time 2: 01:15:25
Python3 Examples