PYTHON TOOL FUNCTION
把任意秒数,变成一眼能懂的中文时长
seconds_to_human(seconds) 是一个纯 Python 工具函数:非负整数秒进、人类可读中文时长出。0 秒、整分整时整天、跳过零单位、不足 1 秒进位舍入、负数抛错——边界全部处理,并附带 18 组单元测试。
# 文件:seconds_to_human.py —— 函数、测试、使用说明一体化
def seconds_to_human(seconds: int) -> str:
"""3661 -> '1小时1分1秒' · 86400 -> '1天' · -1 -> ValueError"""
01
交互演示
与 Python 函数同一套换算逻辑(含四舍五入与负数拦截)
OUTPUT · seconds_to_human()
1小时1分1秒
02
四条处理规则
每一条都有对应测试用例兜底
🧱
零秒边界
输入 0 返回「0秒」,不输出空串;1 是最小正整数秒。
⏭️
跳过零单位
整单位自动精简:3600 → 1小时、86400 → 1天、86461 → 1天1分1秒(跳过 0 小时)。
🎯
进位舍入
不足 1 秒四舍五入:0.4 → 0秒、0.6 → 1秒,杜绝「0.4秒」这种尴尬输出。
🛡️
负数拦截
负数输入直接抛出 ValueError,报错文案写明实际收到的值与合法范围。
03
真实运行结果
python3 seconds_to_human.py · 一条命令完成演示+测试
Terminal — python3 seconds_to_human.py
$ python3 seconds_to_human.py
============================================================
seconds_to_human 功能演示
============================================================
0 秒 -> 0秒
1 秒 -> 1秒
45 秒 -> 45秒
60 秒 -> 1分
61 秒 -> 1分1秒
3600 秒 -> 1小时
3661 秒 -> 1小时1分1秒
86400 秒 -> 1天
90061 秒 -> 1天1小时1分1秒
359999 秒 -> 4天3小时59分59秒
============================================================
单元测试运行结果
============================================================
test_59_seconds ... ok
test_bool_raises_type_error ... ok
test_day_and_hour ... ok
test_day_hour_minute_second ... ok
test_day_skip_zero_hour ... ok
test_exact_day ... ok
test_exact_hour ... ok
test_exact_minute ... ok
test_hour_minute_second ... ok
test_large_value ... ok
test_minute_and_second ... ok
test_negative_float_raises_value_error ... ok
test_negative_raises_value_error ... ok
test_non_numeric_raises_type_error ... ok
test_round_down_under_one_second ... ok
test_round_up_under_one_second ... ok
test_single_second ... ok
test_zero_seconds ... ok
----------------------------------------------------------------------
Ran 18 tests in 0.001s
OK
04
用例速查表
18 组用例中的 12 组代表 · 全部来自真实运行输出
| 输入 | 输出 | 用例类型 |
0 | 0秒 | 边界 |
1 | 1秒 | 边界 |
59 | 59秒 | 边界 |
60 | 1分 | 整单位 |
3600 | 1小时 | 整单位 |
3661 | 1小时1分1秒 | 题目示例 |
86400 | 1天 | 跳0单位 |
86461 | 1天1分1秒 | 跳0单位 |
90061 | 1天1小时1分1秒 | 题目示例 |
359999 | 4天3小时59分59秒 | 大数值 |
0.4 / 0.6 | 0秒 / 1秒 | 进位舍入 |
-1 / "100" / True | ValueError / TypeError | 异常输入 |
05
两分钟上手
单文件交付 · 无任何第三方依赖
# 方式一:作为库导入
from seconds_to_human import seconds_to_human
seconds_to_human(3661) # '1小时1分1秒'
seconds_to_human(86400) # '1天'
seconds_to_human(0) # '0秒'
# 方式二:命令行直接运行
# 自动打印功能演示 + 执行全部 18 组单元测试
$ python3 seconds_to_human.py
# 或使用 pytest 只跑测试
$ pytest seconds_to_human.py -v