You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Shell或Python中对HH:MM:SS时间与秒数进行加减计算?

在Shell和Python中处理HH:MM:SS与秒数的加减

Shell 实现

加法操作

以07:12:54加上2000.234秒为例,核心思路是将时间转换为总秒数进行运算,再转回HH:MM:SS格式。

GNU/Linux 环境(GNU Date)

# 定义原始时间和要添加的秒数
original_time="07:12:54"
add_seconds=2000.234

# 将HH:MM:SS转为总秒数,加上目标秒数
total_seconds=$(date -d "$original_time" +%s)
total_seconds=$(echo "$total_seconds + $add_seconds" | bc)

# 转回带三位小数的HH:MM:SS格式
result=$(date -d "@$total_seconds" +%T.%3N)
echo $result

执行后输出:07:46:14.234

macOS/BSD 环境(BSD Date)

BSD Date参数与GNU版本略有差异,需指定输入格式:

original_time="07:12:54"
add_seconds=2000.234

# 转换为总秒数并运算
total_seconds=$(date -j -f "%H:%M:%S" "$original_time" +%s)
total_seconds=$(echo "$total_seconds + $add_seconds" | bc)

# 转回目标格式
result=$(date -j -f "%s" "$total_seconds" +%T.%3N)
echo $result

减法操作

只需将加法中的+替换为-即可:

# GNU/Linux 示例
original_time="07:12:54"
sub_seconds=2000.234

total_seconds=$(date -d "$original_time" +%s)
total_seconds=$(echo "$total_seconds - $sub_seconds" | bc)
result=$(date -d "@$total_seconds" +%T.%3N)
echo $result

执行后输出:06:39:33.766

Python 实现

利用datetime模块的timedelta可以轻松处理带小数的秒数加减。

加法操作

from datetime import datetime, timedelta

original_time_str = "07:12:54"
add_seconds = 2000.234

# 解析时间字符串,构造datetime对象(日期任意,仅关心时分秒)
original_time = datetime.strptime(original_time_str, "%H:%M:%S").time()
dt = datetime(2000, 1, 1, original_time.hour, original_time.minute, original_time.second)

# 执行加法并格式化输出(保留三位小数)
dt += timedelta(seconds=add_seconds)
result = dt.strftime("%H:%M:%S.%f")[:-3]
print(result)

输出结果:07:46:14.234

减法操作

将加法中的+=替换为-=即可:

from datetime import datetime, timedelta

original_time_str = "07:12:54"
sub_seconds = 2000.234

original_time = datetime.strptime(original_time_str, "%H:%M:%S").time()
dt = datetime(2000, 1, 1, original_time.hour, original_time.minute, original_time.second)

dt -= timedelta(seconds=sub_seconds)
result = dt.strftime("%H:%M:%S.%f")[:-3]
print(result)

输出结果:06:39:33.766


内容的提问来源于stack exchange,提问作者gwsmelo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.13 09:22:36