如何让Python中timedelta超24小时仍以hh:mm:ss格式输出
解决timedelta超过24小时显示天数的问题
嘿,这个问题我之前也碰到过!datetime.timedelta 默认的字符串输出确实会把超过24小时的部分拆成天数显示,但我们可以自己手动计算总时长的小时、分钟、秒,然后格式化成想要的 hh:mm:ss 格式。
核心思路
timedelta 对象提供了 total_seconds() 方法,可以获取总时长的秒数。我们可以基于这个数值,通过整除和取余运算拆解出总小时数(不受24小时限制)、剩余分钟和秒:
- 计算总秒数:
total_seconds = int(total.total_seconds()) - 总小时 = 总秒数 // 3600(3600秒=1小时)
- 剩余秒数 = 总秒数 % 3600
- 分钟 = 剩余秒数 // 60
- 秒 = 剩余秒数 % 60
最后用字符串格式化把分钟和秒补零到两位,小时保持原样即可(支持任意位数,比如30小时、100小时都能正常显示)。
修改你的代码
找到你代码中输出总时长的那一行:
print("The total duration is: " + str(total))
替换成以下代码:
total_seconds = int(total.total_seconds()) total_hours = total_seconds // 3600 remaining_secs = total_seconds % 3600 mins = remaining_secs // 60 secs = remaining_secs % 60 # 格式化输出,分钟和秒补零为两位 print(f"The total duration is: {total_hours}:{mins:02d}:{secs:02d}")
额外小优化
你代码里的导入语句有点小问题:
import datetime from datetime import timedelta
应该改成以下二者之一:
- 只导入timedelta:
from datetime import timedelta,这样后面直接用timedelta(hours=...) - 导入整个datetime模块:
import datetime,后面用datetime.timedelta(...)(和你现有代码的用法一致)
修改后的完整代码
from datetime import timedelta # intro print("Welcome to TimeCalc") print("Calculating Durations") clear = True while clear == True: # first input firstNumber = True while firstNumber == True: time_1 = input("Please enter a time [hh:mm:ss] including 0s: ") if len(time_1) > 0 and len(time_1) >= 8 and time_1[-6] == ":" and time_1[-3] == ":" and int(time_1[-5:-3]) < 60 and int(time_1[-2:]) < 60: hours_1 = time_1[:-6] minutes_1 = time_1[-5:-3] seconds_1 = time_1[-2:] hours_1 = int(hours_1) minutes_1 = int(minutes_1) seconds_1 = int(seconds_1) firstNumber = False else: print("Invalid Syntax") time_1 = timedelta(hours=hours_1, minutes=minutes_1, seconds=seconds_1) cont = True while cont == True: # second input secondNumber = True while secondNumber == True: time_2 = input("Please enter a time to add [hh:mm:ss] including 0s: ") if len(time_2) > 0 and len(time_2) >= 8 and time_2[-6] == ":" and time_2[-3] == ":" and int(time_2[-5:-3]) < 60 and int(time_2[-2:]) < 60: hours_2 = time_2[:-6] minutes_2 = time_2[-5:-3] seconds_2 = time_2[-2:] hours_2 = int(hours_2) minutes_2 = int(minutes_2) seconds_2 = int(seconds_2) secondNumber = False else: print("Invalid Syntax") time_2 = timedelta(hours = hours_2, minutes = minutes_2, seconds = seconds_2) total = time_1 + time_2 # 自定义格式化输出 total_seconds = int(total.total_seconds()) total_hours = total_seconds // 3600 remaining_secs = total_seconds % 3600 mins = remaining_secs // 60 secs = remaining_secs % 60 print(f"The total duration is: {total_hours}:{mins:02d}:{secs:02d}") # continue, clear, or exit choice = input("Continue: Y | Clear: N | Exit: X: ") if choice == "Y" or choice == "y": time_1 = total elif choice == "N" or choice == "n": cont = False elif choice == "X" or choice == "x": quit()
这样修改后,不管总时长是25小时还是100小时,都会以hh:mm:ss的格式显示,比如25小时30分15秒会输出25:30:15。
内容的提问来源于stack exchange,提问作者Arryn McLean
相关产品推荐
相关产品推荐

