如何计算第一天和第二天之间的时间(Python)

时间:2014-12-25 03:53:30

标签: python date time

 from datetime import datetime

 FMT = '%H%M'
 rate1 = 35.34 
 Midnight = "0000"

signOnSun1 = raw_input("What time did you sign on Sunday: ");
signOffSun1 = raw_input("What time did you sign off Sunday: ");

totalShift = (datetime.strptime(signOffSun1, FMT) - datetime.strptime (signOnSun1,   FMT))

midnightToSignOff = (datetime.strptime(signOffSun1, FMT) - datetime.strptime (Midnight, FMT))
midnightToSignOff = diff.total_seconds()/60.0/60

基本上这就是我所拥有的。如果我在1800年签到并在0200那天晚上签字我无法回复8 8小时的正确答案

1 个答案:

答案 0 :(得分:0)

问题是程序不知道第二天的转变结束了。为此,您可以检查登录时间是否晚于签收时间,如果是这样,请在签收时添加一天。

from datetime import datetime, timedelta

FMT = '%H%M'
sign_on_time_str = raw_input("What time did you sign on Sunday: ");
sign_off_time_str = raw_input("What time did you sign off Sunday: ");
sign_on_time = datetime.strptime(sign_on_time_str, FMT)
sign_off_time = datetime.strptime(sign_off_time_str, FMT)

if sign_on_time > sign_off_time:
    sign_off_time += timedelta(days=1)

total_shift = sign_off_time - sign_on_time
print total_shift.total_seconds() / 60 / 60