pd.to_timedelta(unit='m')不生效,如何格式化负时长为小时制显示?
解决方案
要把带日期的Timedelta转换成-HH:MM:SS格式的超时/剩余时间,你可以跳过直接存储pd.to_timedelta的结果,转而基于总秒数计算并格式化时分秒:
方法一:直接基于分钟数计算格式化
不需要先转成Timedelta,直接用actual_time_left的分钟数计算总秒数,再拆解成时分秒:
actual_time_left = float(sla_dict.get(df.loc[i,'SLA Type']) - df.loc[i,'time in queue'].total_seconds()/60) # 计算总秒数 total_seconds = actual_time_left * 60 # 处理正负号 sign = "-" if total_seconds < 0 else "" abs_seconds = abs(total_seconds) # 拆解小时、分钟、秒 hours = int(abs_seconds // 3600) minutes = int((abs_seconds % 3600) // 60) seconds = int(abs_seconds % 60) # 格式化为HH:MM:SS,不足两位补零 df.loc[i,'actual time left'] = f"{sign}{hours:02d}:{minutes:02d}:{seconds:02d}"
方法二:转换已有的Timedelta列
如果已经生成了带天数的Timedelta列,可以用total_seconds()提取总时长后再格式化:
# 假设已存在Timedelta类型的'actual time left'列 td = df.loc[i,'actual time left'] total_seconds = td.total_seconds() sign = "-" if total_seconds < 0 else "" abs_seconds = abs(total_seconds) hours = int(abs_seconds // 3600) minutes = int((abs_seconds % 3600) // 60) seconds = int(abs_seconds % 60) df.loc[i,'actual time left'] = f"{sign}{hours:02d}:{minutes:02d}:{seconds:02d}"
说明
这两种方法都绕开了Timedelta自动生成带天数格式的逻辑,通过总秒数直接拆解出小时、分钟、秒,最终输出你需要的纯时分秒带符号格式。比如你的示例中actual_time_left=-221.71会转换成-03:41:43,若超时240分钟则输出-04:00:00。
内容的提问来源于stack exchange,提问作者Soumya Pandey
相关产品推荐
相关产品推荐

