因此,我定义了一个函数,使其返回两个Time
对象的总和作为新的Time
对象,但是结果Time
对象中的分钟总和不能超过59而且我不知道如何实现。
这是我的代码:
from timer import Time
sum_of_time = Time(0, 0)
sum_of_time.hours= time1.hours + time2.hours
sum_of_time.minutes = time1.minutes + time2.minutes
return sum_of_time
if sum_of_time.minutes >= 60: # where I try to make minutes within 0 to 59
sum_of_time.minutes = sum_of_time.minutes - 60
sum_of_time.hours = sum_of_time.hours + 1
return sum_of_time
答案 0 :(得分:1)
这就是datetime.timedelta的用途。
from datetime import timedelta
delta1 = timedelta(hours=1, minutes=30)
delta2 = timedelta(minutes=31)
sum_time = delta1 + delta2
print(sum_time) #2:01:00
答案 1 :(得分:0)
您想除以60的商和余数;商被加到小时,其余的用作分钟数。
sum_of_time = Time(0,0)
hours = time1.hours + time2.hours
minutes = time1.minutes + time2.minutes
q, r = divmod(minutes, 60) # e.g. divmod(117, 60) == (1, 57)
hours += q
minutes = r
sum_of_time.hours = hours
sum_of_time.minutes = minutes
这可能应该由Time
类的方法来实现。例如:
class Time:
def __init__(self, h, m):
self.hours = 0
self.minutes = 0
# For simplicity here, assume other is an instance of Time
def __add__(self, other):
hours = self.hours + other.hours
minutes = self.minutes + other.minutes
q, r = divmod(minutes, 60)
return Time(hours + q, r)
sum_of_time = time1 + time2
答案 2 :(得分:0)
class Time:
def __init__(self,h,m):
self.h = h
self.m = m
q, r = divmod(m, 60)
self.h += q
self.m = r
def __add__(self, o):
return Time(self.h+o.h,self.m+o.m)
def __str__(self):
return "{0}:{1}".format(self.h,self.m)
t1 = Time(1,60)
t2 = Time(1,60)
print (t1+t2)