1 import time as t 2 3 class Mytimer: 4 5 def __init__(self): 6 self.prompt = '未开始计时' 7 self.unit = ['年','月','日','时','分','秒'] 8 self.begin = 0 9 self.end = 0 10 self.list=[]#定义列表存储时间差 11 12 def __str__(self): 13 return self.prompt 14 15 __repr__ = __str__ 16 17 def __add__(self, other): 18 prompt = '共计用时' 19 for index in range(6): 20 if self.list[index] != 0 or other.list[index] != 0: 21 prompt += str(int(self.list[index])+ int(other.list[index]))+self.unit[index] 22 return prompt 23 24 25 #开始计时 26 def start(self): 27 print('现在开始计时……') 28 self.begin = t.localtime() 29 if self.end == 0: 30 self.prompt = '请先stop()' 31 32 #停止计时 33 def stop(self): 34 if self.begin == 0: 35 print('请先start()') 36 else: 37 print('停止计时!') 38 self.end = t.localtime() 39 self._cals() 40 41 #内部方法计算时间差 42 def _cals(self): 43 44 self.prompt = '总共运行了' 45 for index in range(6): 46 temp = self.end[index] - self.begin[index] 47 if temp < 0: 48 #测试高位是否有的借,没有的借的话向再高位借…… 49 i = 1 50 while self.list[index-i]<1: 51 self.list[index-i] += self.borrow[index-i] - 1 52 self.list[index-i-1] -= 1 53 i += 1 54 self.list.append(self.borrow[index]+temp) 55 self.list[index-1] -= 1 56 else: 57 self.list.append(temp) 58 #由于高位随时会被借位,因此打印放在最后 59 for index in range(6): 60 if self.list[index]: 61 self.prompt += str(self.list[index]) + self.unit[index] 62 return self.prompt