如果你只是想增加小时、分钟、秒并创建一个字符串:
def weird_time(current_time,duration):
start = datetime.strptime(current_time, "%H:%M:%S")
st_hr, st_min, st_sec = start.hour, start.minute, start.second
mn, secs = divmod(duration, 60)
hour, mn = divmod(mn, 60)
mn, secs = st_min+mn, st_sec+secs
if secs > 59:
m, secs = divmod(secs,60)
mn += m
if mn > 59:
h, mn = divmod(mn,60)
hour += h
return "{:02}:{:02}:{:02}".format(st_hr+hour, mn, secs)
输出:
In [19]: weird_time("23:30:00",7200)
Out[19]: '25:30:00'
In [20]: weird_time("23:30:00",3600)
Out[20]: '24:30:00'
In [21]: weird_time("23:30:59",7203)
Out[21]: '25:31:02'
In [22]: weird_time("23:30:59",3601)
Out[22]: '24:31:00'
我们也可以使用 timedelta 来计算总秒数,并以此进行计算,而不是自己进行所有计算:
from datetime import datetime,timedelta
def weird_time(current_time,duration):
start = datetime.strptime(current_time, "%H:%M:%S")
st_hr, st_min, st_sec = start.hour, start.minute, start.second
comb = timedelta(minutes=st_min,seconds=st_sec) + timedelta(seconds=duration)
mn, sec = divmod(comb.total_seconds(), 60)
hour, mn = divmod(mn, 60)
return "{:02}:{:02}:{:02}".format(int(st_hr+hour), int(mn), int(sec))
输出相同:
In [29]: weird_time("23:30:00",7200)
Out[29]: '25:30:00'
In [30]: weird_time("23:30:00",3600)
Out[30]: '24:30:00'
In [31]: weird_time("23:30:59",7203)
Out[31]: '25:31:02'
In [32]: weird_time("23:30:59",3601)
Out[32]: '24:31:00'
In [33]: weird_time("05:00:00",3600)
Out[33]: '06:00:00'
小时只需要增加,我们需要捕获的部分是秒、分钟或两者的总和大于 59。