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

如何用Python实现时间减法?datetime库24:00格式报错处理

Python内置库实现时间差计算(兼容24:00:00格式)

需求与自定义实现

需求为计算24:00:00与14:20:10的时间差,已自定义实现time_minus函数完成计算:

def time_minus(start,end):
    def convert_sec(time):
        hours = int(time.split(":")[0])
        mins = int(time.split(":")[1])
        secs = int(time.split(":")[2])
        return hours*60*60 + mins*60 + secs
    start_time = convert_sec(start)
    end_time = convert_sec(end)   
    st = end_time-start_time
    hours = str(st//3600).rjust(2,'0')
    mins = str((st%3600)//60).rjust(2,'0')
    secs = str((st%3600)%60).rjust(2,'0')
    result = hours +  " hours " + mins +  " minutes " + secs + " seconds"
    print(result)
    return  hours + ":" + mins +  ":" + secs 

函数执行输出:

x=time_minus("14:20:10","24:00:00")  
# 输出:09 hours 39 minutes 50 seconds  
x
# 返回:'09:39:50'

疑问:内置库能否实现?datetime报错原因

使用datetime库时出现报错,是因为%H格式符仅支持00-23的小时范围,24:00:00不符合该格式规则,因此解析失败:

>>> from datetime import datetime
>>> s1 = '14:20:10'
>>> s2 = '24:00:00'  
>>> FMT = '%H:%M:%S'
>>> tdelta = datetime.strptime(s2, FMT) - datetime.strptime(s1, FMT)
# 报错:ValueError: time data '24:00:00' does not match format '%H:%M:%S'

内置库的正确实现方式

方法1:处理24:00:00为次日00:00:00

通过判断特殊格式,将24:00:00转换为次日的00:00:00,再用datetime和timedelta计算:

from datetime import datetime, timedelta

s1 = '14:20:10'
s2 = '24:00:00'
FMT = '%H:%M:%S'

# 处理24:00:00的特殊情况
if s2 == '24:00:00':
    t2 = datetime.strptime('00:00:00', FMT) + timedelta(days=1)
else:
    t2 = datetime.strptime(s2, FMT)

t1 = datetime.strptime(s1, FMT)
time_diff = t2 - t1

# 格式化输出结果
total_hours = time_diff.days * 24 + time_diff.seconds // 3600
total_mins = (time_diff.seconds % 3600) // 60
total_secs = time_diff.seconds % 60

print(f"{total_hours:02d} hours {total_mins:02d} minutes {total_secs:02d} seconds")
# 输出:09 hours 39 minutes 50 seconds
print(f"{total_hours:02d}:{total_mins:02d}:{total_secs:02d}")
# 输出:09:39:50

方法2:直接转换为timedelta对象计算

利用timedelta处理时间间隔,无需依赖datetime的日期解析:

from datetime import timedelta

def str_to_timedelta(time_str):
    hours, mins, secs = map(int, time_str.split(':'))
    return timedelta(hours=hours, minutes=mins, seconds=secs)

s1 = '14:20:10'
s2 = '24:00:00'

delta1 = str_to_timedelta(s1)
delta2 = str_to_timedelta(s2)
time_diff = delta2 - delta1

# 格式化输出
total_seconds = time_diff.total_seconds()
hours = int(total_seconds // 3600)
mins = int((total_seconds % 3600) // 60)
secs = int(total_seconds % 60)

print(f"{hours:02d} hours {mins:02d} minutes {secs:02d} seconds")
# 输出:09 hours 39 minutes 50 seconds
print(f"{hours:02d}:{mins:02d}:{secs:02d}")
# 输出:09:39:50

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 15:45:49