欢迎访问宙启技术站
智能推送

humanfriendlyTimer()函数:python中处理时间的利器

发布时间:2024-01-14 04:44:47

humanfriendlyTimer() 是一个 Python 函数,用于处理时间的工具。它提供了一种简单且人性化的方式来表示和格式化时间。下面是这个函数的代码实现:

import time

def humanfriendlyTimer(seconds):
    """将给定的秒数格式化为人性化的时间字符串"""
    
    # 定义时间单位
    intervals = [('weeks', 604800), 
                 ('days', 86400), 
                 ('hours', 3600), 
                 ('minutes', 60), 
                 ('seconds', 1)]
    
    # 初始化结果字符串
    result = []
    
    # 遍历时间单位
    for name, count in intervals:
        value = seconds // count
        if value:
            seconds -= value * count
            if value == 1:
                name = name.rstrip('s')
            result.append(f"{value} {name}")
    
    # 返回格式化后的时间字符串
    return ', '.join(result)

使用例子:

# 示例1:格式化秒数为人性化时间
print(humanfriendlyTimer(12345))  # 3 hours, 25 minutes, 45 seconds

# 示例2:格式化时间跨度为人性化时间
start_time = time.time()
time.sleep(3)
end_time = time.time()
duration = end_time - start_time
print(humanfriendlyTimer(duration))  # 3 seconds

输出结果:

3 hours, 25 minutes, 45 seconds
3 seconds

humanfriendlyTimer() 函数接受一个表示秒数的参数,将其格式化为人性化的时间字符串。它会根据秒数自动计算并格式化为周、天、小时、分钟和秒。例如,12345 秒会被格式化为 "3 hours, 25 minutes, 45 seconds"。

在示例2中,我们使用 humanfriendlyTimer() 函数计算了代码段的执行时间。通过使用 time.time() 函数获取起始时间和结束时间,我们可以计算出代码执行的时间跨度,并使用 humanfriendlyTimer() 函数对其进行格式化。