【Python tools 时间】

打印运行时间

import time


class PrintRunCycle(object):
    def __init__(self):
        self._start_time = None

    def __enter__(self):
        self._start_time = time.time()

    def __exit__(self, exc_type, exc_val, exc_tb):
        end_time = time.time()
        print(f"运行时间: {end_time - self._start_time}s")


if __name__ == '__main__':
    with PrintRunCycle():
        print("---")

固定运行周期

import time


class FixedCycle(object):
    def __init__(self, cycle_time):
        """
        运行消耗时间 + 休眠时间 >= cycle_time
        ①如果运行代码有异常,直接抛弃,不休眠
        ②如果 cycle_time < 运行代码时间,不会强制终止运行, 优先将代码执行完
        :param cycle_time: 单位 s
        """
        self._cycle_time = cycle_time

    def __enter__(self):
        self._start_time = time.time()

    def __exit__(self, exc_type, exc_val, exc_tb):
        if exc_type or exc_val or exc_tb:
            return
        end_time = time.time()
        run_cycle = end_time - self._start_time
        need_sleep_time = max(self._cycle_time - run_cycle, 0)
        print(f"运行消耗{run_cycle}s, 需要休眠{need_sleep_time}s")
        time.sleep(need_sleep_time)


if __name__ == '__main__':
    with FixedCycle(10):
        print("joshua")

时间转时间戳

def time_in_timestamp(time_str: str, time_format="%Y-%m-%d %H:%M:%S") -> int:
    """
    时间转时间戳
    :return: 时间戳  单位:毫秒
    """
    return int(time.mktime(time.strptime(time_str, time_format)) * 1000)

时间戳转时间

def timestamp_in_time(timestamp: int, time_format="%Y-%m-%d %H:%M:%S") -> str:
    """
    时间戳转时间
    :return: 时间字符串
    """
    return time.strftime(time_format, time.localtime(timestamp * 0.001))
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值