python发现两次之间的一半时间

时间:2016-02-22 10:34:06

标签: python

我希望在python中找到两次之间的一半时间。假设我有两次

start_time = '08:30:00'
end_time = '16:30:00'

如果要显示上半部分,则应打印为'08:30:00' and '12:30:00' 如果我想显示后半部分,则应打印为'12:30:00' and '16:30:00'

任何建议都会有所帮助。

2 个答案:

答案 0 :(得分:0)

from datetime import datetime
a = '08:30:00'
b = '16:30:00'
FMT = '%H:%M:%S'
delta = datetime.strptime(b, FMT) - datetime.strptime(a, FMT)
half = datetime.strptime(a, FMT) + delta/2
print a + ' - ' + str(datetime.time(half))
print str(datetime.time(half)) + ' - ' + b

答案 1 :(得分:0)

使用python datetime module

from datetime import timedelta, datetime

start_time = '08:30:00'
end_time = '16:30:00'
time_format = '%H:%M:%S'

# Convert to the datetime object
start = datetime.strptime(start_time, time_format)
end = datetime.strptime(end_time, time_format)

# Find half of delta between start and end
half_seconds = (end - start).total_seconds() / 2
half = start + timedelta(seconds=half_seconds)

print(half.strftime(time_format))
print(end.strftime(time_format))