我尝试在两次之间获得中途时间,这是我尝试的代码,但是没有用。
import datetime
import time
start_time = datetime.datetime.now().time().strftime('5:00')
end_time = datetime.datetime.now().time().strftime('7:00')
total_time=(datetime.datetime.strptime(end_time,'%H:%M') +
datetime.datetime.strptime(start_time,'%H:%M'))
total_time = total_time / 2
print (total_time)
答案 0 :(得分:0)
您不能添加两个日期时间。 Python(和大多数语言)区分时间戳和经过时间(持续时间)。您可以执行的操作:
(当然,在许多情况下使用不同的语言,时间戳实际上是从预定时间点开始经过的时间,在这些情况下,两者可以互换使用,但不幸的是,在这种情况下并不能使用。)< / p>
import datetime
import time
start_time = datetime.datetime.now().time().strftime('5:00')
end_time = datetime.datetime.now().time().strftime('7:00')
time1 = datetime.datetime.strptime(start_time,'%H:%M')
time2 = datetime.datetime.strptime(end_time,'%H:%M')
duration = time2 - time1
midtime = time1 + duration/2
print(midtime.strftime("%H:%M"))
# output
#06:00
已修改:对于开始时间在结束时间之后的情况(因此开始时间实际上在第二天)
import datetime
def midtime(time1, time2):
# advance start time by 1 day if the start time is after the end time
if time1 > time2:
time1 += datetime.timedelta(1)
duration = time2 - time1
midtime = time1 + duration/2
return midtime.strftime("%H:%M")
stime = datetime.datetime.strptime
print('Midtime between 8pm and 6am is', midtime(stime('20:00', '%H:%M'), stime('6:00', '%H:%M')))
print('Midtime between 7pm and 5am is', midtime(stime('19:00', '%H:%M'), stime('5:00', '%H:%M')))
print('Midtime between 6am and 8pm is', midtime(stime('6:00', '%H:%M'), stime('20:00', '%H:%M')))
print('Midtime between 5am and 7pm is', midtime(stime('5:00', '%H:%M'), stime('19:00', '%H:%M')))
# output
#Midtime between 8pm and 6am is 01:00
#Midtime between 7pm and 5am is 00:00
#Midtime between 6am and 8pm is 13:00
#Midtime between 5am and 7pm is 12:00