简体   繁体   中英

python)How can I calculate difference between two times in mininute

I tried it by this way

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)

but there is too many prob such as cannot calculate between PM and AM and also

i cant use - with str.

I don't know how to use the module for now so anyone can help me? :CI took more than 12 hours for this and tried to find the help at the Google but all of the samples are using the module ... help me!!

You should use datetime objects for this:

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)

Sample Input:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM