1. 自制定时器
class Mytimer():
def __init__(self):
self.__tips='未开始计时!'
self.__unit=['年', '月', '日', '小时', '分钟', '秒']
self.__borrow=[0,12,31,24,60,60]
self.__lasted = []
self.__startTime = 0 #千万不要让属性名和方法名重复,属性会覆盖方法定义
self.__stopTime = 0
self.__BeginTime=0
def __str__(self):
print('str')
return self.__tips
def __repr__(self):
print('repr')
return self.__tips
#开始计时
def start(self):
if self.__BeginTime == 0:
self.__startTime = t.localtime()
self.__BeginTime = 1
print('开始计时...')
print(t.localtime())
else:
print('您已经开始计时过了!')
# 停止计时
def stop(self):
self.__stopTime = t.localtime()
if self.__BeginTime==1:
self.__calcTime()
self.__BeginTime=0
print('停止计时...')
print(t.localtime())
else :
print('未开始计时')
#计算运行时间
def __calcTime(self):
self.__lasted =[]
self.__tips='总共运行了:'
for index in range(6):
temp=(self.__stopTime[index]-self.__startTime[index])
#判断进位:
if temp<0:
i=1
while self.__lasted[index-i]<1:
self.__lasted[index-i]+=self.__borrow[index-i]-1
i+=1
self.__lasted.append(self.__borrow[index]+temp)
self.__lasted[index-i]=self.__lasted[index-i]-1
else:
self.__lasted.append(temp)
for index in range(6):
if self.__lasted[index] != 0:
self.__tips += str(self.__lasted[index]) + self.__unit[index]
print(self.__tips)
def __add__(self, other):
time = '总共运行了:'
result=[]
for index in range(6):
result.append(self.__lasted[index] + other.__lasted[index])
if result[index]:
time +=str(result[index])+self.__unit[index]
print(time)
return time
t1=Mytimer()
t1.start()
n=input('随便写写,拖延时间....\n')
t1.stop()
print('=============\n')
print(t1)
2. time模块详解
Eg:
import time as t
print(t.localtime())
print(t.process_time())
print(t.strftime("a, %d %b %Y %H:%M:%S +0000", t.localtime()))