1

I want to find half time between two times in python. Let's say I've two times

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

If I want to display first half, it should print as'08:30:00' and '12:30:00' If I want to display second half, it should print as '12:30:00' and '16:30:00'

Any suggestions would be helpful.

sky
  • 21
  • 3

2 Answers2

1

Use a 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))
Nikolai Golub
  • 3,327
  • 4
  • 31
  • 61
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
Benjamin
  • 2,257
  • 1
  • 15
  • 24
yael
  • 307
  • 1
  • 7