Python将小时,分钟和秒添加到已创建的时间

时间:2017-09-24 07:21:00

标签: python-3.x

如何将小时,分钟和秒添加到我创建的时间?

代码:

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

1 个答案:

答案 0 :(得分:1)

您想使用timedelta对象:

from datetime import timedelta
t1 = datetime.time(hours, minutes, second) + timedelta(seconds=s, minutes=m, hours=h)

并且其中sm可以大于59,h更大23而没有问题