跳到内容
🛠️ToolsShed

时间计算器

加减小时、分钟和秒来计算时间段。

关于此工具

时间长度计算器替你对小时、分钟和秒进行加减,也能算出起始时间与结束时间之间的间隔。当你只想得到一个干净的总数时,它让你免去把秒进位到分、把分进位到时这种容易出错的心算。

输入时间数值,选择把它们相加、相减,还是测量两个时刻之间的跨度,结果便会立即显示。它非常适合填写考勤表、剪辑视频和音频、记录烹饪与烘焙的各个阶段、登记锻炼分段,以及统计可计费工时。

计算器会自动处理每一次进位,把90秒换算成1分30秒,把75分钟换算成1小时15分钟,不会出现任何取整意外。一切都完全在你的浏览器中运行,所以数据留在你的设备上,即使离线也能即时得到结果。

常见问题

代码实现

import re

def parse_duration(s: str) -> int:
    """Parse a duration string like '1h 30m 45s' into total seconds."""
    pattern = r'(?:(d+)s*dw*)?s*(?:(d+)s*hw*)?s*(?:(d+)s*mw*)?s*(?:(d+)s*sw*)?'
    match = re.fullmatch(pattern.strip(), s.strip(), re.IGNORECASE)
    if not match or not any(match.groups()):
        raise ValueError(f"Cannot parse duration: {s!r}")
    d, h, m, sec = (int(x or 0) for x in match.groups())
    return d * 86400 + h * 3600 + m * 60 + sec

def format_duration(seconds: int) -> str:
    """Format total seconds back to a human-readable string."""
    seconds = abs(int(seconds))
    d = seconds // 86400
    h = (seconds % 86400) // 3600
    m = (seconds % 3600) // 60
    s = seconds % 60
    parts = []
    if d: parts.append(f"{d}d")
    if h: parts.append(f"{h}h")
    if m: parts.append(f"{m}m")
    if s or not parts: parts.append(f"{s}s")
    return " ".join(parts)

def add_durations(*durations: str) -> str:
    total = sum(parse_duration(d) for d in durations)
    return format_duration(total)

# Examples
print(parse_duration("1h 30m"))       # 5400
print(parse_duration("2d 4h 15m 0s")) # 187500
print(format_duration(5400))          # "1h 30m"
print(add_durations("1h 30m", "45m", "2h 15m"))  # "4h 30m"

Comments & Feedback

Comments are powered by Giscus. Sign in with GitHub to leave a comment.