import time as t
class Mytimer():
# 开始计时器
def start(self):
self.start = t.localtime()
print('开始计时…')
# 停止计时器
def stop(self):
self.stop = t.localtime()
self._calc()
print('计时结束!')
# 内部方法,计时运行时间
def _clac(self):
self.lasted = []
self.prompt = '总共运行了'
for index in range(6):
self.lasted.append(self.stop(index) - self.start(index))
self.prompt += str(self.lasted(index))
print(self.prompt)
下面是我的理解,供参考:
首先stop()函数里面调用的self._calc()的_calc()这个函数名写错了,定义的计算函数是 _clac(self),这里把stop()函数里面调用的self._calc()改为self._clac()
然后t.localtime() 把时间戳转换为struct_time对象格式,默认返回当前时间戳,所以从这个对象取时间值,以及对他进行计算,需要使用特定的方法,直接使用元组形式的访问可能不太准确。参考网络搜索的资料,我把代码修改了一下,如下:
参考链接:
python的localtime函数_python的内置函数time_weixin_39875675的博客-CSDN博客
python利用时间戳计算时间差_fff2zrx的博客-CSDN博客_python 时间戳计算时间差
(实例解析)Python 函数调用的几种方式(类里面,类之间,类外面)_一纸春秋的博客-CSDN博客_python调用
python延时函数_好生活好二三四
Python datetime模块详解_zxfBdd的博客-CSDN博客_datetime python
import time as t
import datetime
class Mytimer():
# 开始计时器
def start(self):
#https://blog.csdn.net/weixin_39875675/article/details/110700947
self.start = t.localtime()
print('开始计时…')
# 停止计时器
def stop(self):
self.stop = t.localtime()
self._clac()
print('计时结束!')
# 内部方法,计时运行时间
def _clac(self):
#self.lasted = []
self.prompt = '总共运行了'
#https://blog.csdn.net/qq_38412868/article/details/102016832
#把self.start和self.stop代表时间元祖转换为格式化时间字符串
self.start = t.strftime("%Y-%m-%d %H:%M:%S",self.start)
self.stop = t.strftime("%Y-%m-%d %H:%M:%S",self.stop)
#把self.start和self.stop代表的格式化时间字符串转换为datetime对象时间
time1=datetime.datetime.strptime(self.start,"%Y-%m-%d %H:%M:%S")
time2 = datetime.datetime.strptime(self.stop, "%Y-%m-%d %H:%M:%S")
#datetime对象时间可以直接相减,得出两个时间经过的秒数
#https://blog.csdn.net/u011250186/article/details/103972471
#此处如果还要显示相差多少天(相差大于等于1天时)可以访问他的变量days即可,
#https://blog.csdn.net/u011250186/article/details/103972471
#self.prompt += str((time2-time1).days)+"天,"+str((time2-time1).seconds)+"秒"
self.prompt += str((time2-time1).seconds)+"秒"
print(type(time1))
print(self.prompt)
#https://blog.csdn.net/qq_44823756/article/details/120321352
test = Mytimer()
test.start()
#https://www.how234.com/eamyrzbzr.html
t.sleep(3) #使用延时函数模拟时间流逝,实际使用中用业务代码代替
test.stop()
_clac函数名,你写错了,你拼写的是_clac
l和a的位置反了