Use Python to create a time class that supports time addition and subtraction operations

Document 对象参考手册Python3 Examples

We will create a class namedTimeclass, which can represent time (hours, minutes, seconds) and supports time addition and subtraction operations. We will implement__add__and__sub__methods to support time addition and subtraction operations.

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)

print("Time 1:", time1)
print("Time 2:", time2)

time_sum = time1 + time2
print("Time 1 + Time 2:", time_sum)

time_diff = time1 - time2
print("Time 1 - Time 2:", time_diff)

Code analysis:

  1. __init__Method: initializationTimethe class instance, accepts hours, minutes, and seconds as parameters, and callsnormalizemethod to ensure the time format is correct.
  2. normalizeMethod: Convert seconds and minutes to standard format, ensuring seconds do not exceed 59 and minutes do not exceed 59.
  3. __add__Method: implements the addition of twoTimeobjects, converting times to seconds for addition, then converting back to hours, minutes, and seconds.
  4. __sub__Method: implements the subtraction of twoTimeobjects, converting times to seconds for subtraction, then converting back to hours, minutes, and seconds.
  5. __str__Method: returns a formatted time string, ensuring hours, minutes, and seconds are 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

Document 对象参考手册Python3 Examples

Other extensions