Python耗费时间秒转 天小时分钟秒 时间格式美化

在工作中经常会遇到将耗时 转换为小时秒的情况

本Demo 中divmod默认返回元组,同时利用递归的思想

# -*- coding: utf-8 -*-


def seconds_format(time_cost: int):
    """
    耗费时间格式转换
    :param time_cost: 
    :return: 
    """
    min = 60
    hour = 60 * 60
    day = 60 * 60 * 24
    if not time_cost or time_cost < 0:
        return ''
    elif time_cost < min:
        return '%s秒' % time_cost
    elif time_cost < hour:
        return '%s分%s秒' % (divmod(time_cost, min))
    elif time_cost < day:
        cost_hour, cost_min = divmod(time_cost, hour)
        return '%s小时%s' % (cost_hour, seconds_format(cost_min))
    else:
        cost_day, cost_hour = divmod(time_cost, day)
        return '%s天%s' % (cost_day, seconds_format(cost_hour))

if __name__ == '__main__':
	seconds_format(1)
	seconds_format(61)
发布了76 篇原创文章 · 获赞 221 · 访问量 22万+

猜你喜欢

转载自blog.csdn.net/chichu261/article/details/104527492