如何在mininute中计算两次之间的差异

时间:2017-06-01 03:54:18

标签: python python-3.x

我通过这种方式尝试了

time1=input("Enter your first time (ex.xx:xxPM) : ")
am_or_pm1=time1[-2:].upper()
colpos1=time1[2:3]
hour1=time1[0:2]
minute1=time1[3:5]
print('This is your first time')
print(time1)

time2=input("Enter your first time (ex.xx:xxPM) : ")
am_or_pm2=time2[-2:].upper()
colpos2=time2[2:3]
hour2=time2[0:2]
minute2=time2[3:5]
print('This is your second time')
print(time2)

timediff=(time1 - time2)
print(timediff)

但是有太多的问题,例如无法在PM和AM之间计算,也

我无法使用 - 与str。

我现在不知道如何使用该模块,所以任何人都可以帮助我? :C 我花了12个多小时的时间才尝试在谷歌找到帮助但是 所有的样本都在使用模块......帮助我!!

1 个答案:

答案 0 :(得分:1)

您应该使用datetime个对象:

from datetime import datetime

time1=input("Enter your first time (ex.xx:xxPM) : ")
timeObj1 = datetime.strptime(time1,'%I:%M%p')

time2=input("Enter your first time (ex.xx:xxPM) : ")
timeObj2 = datetime.strptime(time2,'%I:%M%p')

print(timeObj1-timeObj2)

样本输入:

Enter your first time (ex.xx:xxPM) : 5:30PM
Enter your first time (ex.xx:xxPM) : 5:00PM
0:30:00