因为项目需要输出指定时间间隔和间隔内模块上报的次数,为了避免每次用计算器算,所以自己封装了一个函数,以供自己使用:
import time
def time_unix(old_time):
"""将格式为:'2020-9-18 17:50:00'的时间转成unix表示的时间戳"""
data_sj = time.strptime(old_time,'%Y-%m-%d %H:%M:%S')
time_int = int(time.mktime(data_sj))
return time_int
def count_t(old_t,type,count = 15):
"""返回实际指定时间与现在的时间间隔
old_t:代表以前的时间
count:代表模块上报周期
type:代表类型,值为:‘s’,'m','h'
"""
now_t = time.time()
now_time = time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(int(time.time())))
end_t_s = now_t - time_unix(old_t)
if count == 0:
if type == 's':
return '指定时间:【{}】距离现在【{}】 {:.2f}s'.format(old_t,now_time,end_t_s)
if type == 'm':
return '指定时间:【{}】距离现在【{}】 {:.2f}min'.format(old_t,now_time,end_t_s/60)
if type == 'h':
return '指定时间:【{}】距离现在【{}】 {:.2f}hour'.format(old_t,now_time,end_t_s/60/60)
else:
return '输入有误'
else:
end_t_c = end_t_s / 60 / count
return '指定时间:【{}】距离现在【{}】 {:.2f}s,以{}min为间隔,共{}次'.format(old_t,now_time,end_t_s,count,end_t_c)
if __name__ == '__main__':
test1 = '2020-9-18 17:50:00'
print(count_t(test1, 'd', 15))
print(count_t(test1, 'h',0))