如何将小时,分钟和秒添加到我创建的时间?
代码:
import datetime
time_entry = input('Enter a time in hh:mm:ss format:')
hours, minutes, second = map(int, time_entry.split(':'))
t = datetime.time(hours, minutes, second)
h = int(input('Hours:'))
m = int(input('Minutes:'))
s = int(input('Seconds:'))
print('Current time is:',t)
t1 = datetime.time(hours + h, minutes + m, second + s)
print('New time is:',t1)
我希望它能像这样出现:
Enter a time in hh:mm:ss format:23:23:23
Hours:2
Minutes:2
Seconds:2
Current time is: 23:23:23
New time is: 1:25:25
但我得到了:
t1 = datetime.time(hours + h, minutes + m, second + s)
ValueError: hour must be in 0..23
答案 0 :(得分:1)
您想使用timedelta
对象:
from datetime import timedelta
t1 = datetime.time(hours, minutes, second) + timedelta(seconds=s, minutes=m, hours=h)
并且其中s
和m
可以大于59,h
更大23而没有问题