马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
import time as t
class Time():
def __init__(self):
self.unit = ['年','月','日','时','分','秒']
self.prompt = "未开始计时!"
self.lasted = []
self.begin = 0
self.end = 0
self.borrow = [0,12,0,24,60,60]
def __str__(self):
return self.prompt
__repr__ = __str__
#时间相加计算
def __add__(self,other):
prompt = '总共运行了'
result = []
for i in range(6):
result.append(self.lasted[i] + other.lasted[i])
if result[i]:
prompt += (str(result[i]) + self.unit[i])
return prompt
#开始计时
def start(self):
self.begin = t.localtime()
self.prompt = '提示:请先调用stop()停止计时!'
print('计时开始……')
prompt = '开始时间为:'
for i in range(6):
if self.begin[i]:
prompt += (str(self.begin[i]) + self.unit[i])
#时间借位时,借位列表
temp = self.begin [1]
if (temp == 1) or (temp == 3) or (temp == 5) or(temp == 7) or (temp == 8) or (temp == 10) or(temp == 12):
self.borrow[2] = 31
else:
if (temp == 2):
self.borrow[2] = 29
else:
self.borrow[2] = 30
return prompt
#停止计时
def stop(self):
if not self.begin:
print('提示;请先调用start()进行计时')
else:
self.end = t.localtime()
self._cale()
prompt = '结束时间为:'
for i in range(6):
if self.end[i]:
prompt += (str(self.end[i]) + self.unit[i])
self._initialize()
print('计时结束!')
return prompt
#计算运行时间
def _cale(self):
self.lasted = []
self.prompt = "总共运行了"
for i in range(6):
self.lasted.append(self.end[i] - self.begin[i])
#借位操作,计算时间
for i in [5,4,3,2,1,0]:
temp = self.lasted[i]
if temp <0:
j = 1
while self.lasted[i - j] <1:
self.lasted[i - j] += self.borrow[i - j]-1
self.lasted[i - j-1] -= 1
j += 1
self.lasted[i] += self.borrow[i]
self.lasted[i -1] -= 1
for i in range(6):
if self.lasted[i]:
self.prompt += (str(self.lasted[i]) + self.unit[i])
#为下一轮计时初始化
def _initialize(self):
self.begin = 0
self.end = 0
|