如何在Python中将秒数数组转换为dd:hh:mm:ss格式?
实现秒数到dd:hh:mm:ss格式的转换
直接用数学运算拆分秒数是最可靠的方式,能确保不管天数多少都输出正确的总天数格式,代码实现如下:
import numpy as np # 保留你原始的秒数数组生成逻辑 timeSec = np.arange(0, len(time)*(time[2] - time[1])*60, (time[2] - time[1])*60, dtype=int) def format_seconds(s): # 计算总天数 days = s // (24 * 3600) # 拆分剩余秒数为小时、分钟、秒 remaining = s % (24 * 3600) hours = remaining // 3600 remaining %= 3600 minutes = remaining // 60 seconds = remaining % 60 # 格式化两位数字,不足补0 return f"{days:02d}:{hours:02d}:{minutes:02d}:{seconds:02d}" # 向量化函数批量处理numpy数组 vec_format = np.vectorize(format_seconds) formatted_time = vec_format(timeSec)
如果你的时间跨度不会超过31天,也可以借助datetime模块实现,但注意这种方式的%d取的是日历日期中的天数,而非总天数,超过31天会出现错误:
from datetime import datetime, timedelta def format_seconds_v2(s): base_dt = datetime(1970, 1, 1) target_dt = base_dt + timedelta(seconds=s) return f"{target_dt.day:02d}:{target_dt.hour:02d}:{target_dt.minute:02d}:{target_dt.second:02d}" formatted_time_v2 = np.array([format_seconds_v2(s) for s in timeSec])
优先推荐第一种方法,能完全匹配仿真软件要求的dd:hh:mm:ss格式,其中dd代表总天数而非日历日期。
内容的提问来源于stack exchange,提问作者Jerald
相关产品推荐
相关产品推荐

