时间间隔输出函数 python3

因为项目需要输出指定时间间隔和间隔内模块上报的次数,为了避免每次用计算器算,所以自己封装了一个函数,以供自己使用:

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))
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值