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

Python实现将秒数数组转换为HH:MM格式

将秒数数组转换为HH:MM格式数组

Python 实现

核心逻辑是把每个秒数拆解为小时和分钟,再格式化为两位数字的标准字符串:

# 原始秒数数组
time = (900, 1800, 2700, 3661)
# 转换为HH:MM格式的元组
time_new = tuple(f"{s//3600:02d}:{(s%3600)//60:02d}" for s in time)

print(time_new)
# 输出结果: ('00:15', '00:30', '00:45', '01:01')

代码说明:

  • s//3600:通过整数除法计算总小时数
  • (s%3600)//60:先取模3600得到剩余秒数,再转换为分钟
  • :02d:强制格式化为两位数字,不足时前面补0,保证格式统一

JavaScript 实现

如果需要在前端环境处理,可使用数组map方法遍历转换:

const time = [900, 1800, 2700, 3661];
const time_new = time.map(seconds => {
  const hours = Math.floor(seconds / 3600).toString().padStart(2, '0');
  const minutes = Math.floor((seconds % 3600) / 60).toString().padStart(2, '0');
  return `${hours}:${minutes}`;
});

console.log(time_new);
// 输出结果: ['00:15', '00:30', '00:45', '01:01']

代码说明:

  • Math.floor(seconds / 3600):计算小时数并向下取整
  • padStart(2, '0'):将数字转为字符串后,不足两位时在前面补0

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 20:33:22