0

I try to get mid time between two time, here is my code which i tried but it didn't work.

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)
Avinash
  • 133
  • 9
Sana ullah
  • 21
  • 7
  • 2
    Your argument to `strftime()` is not correct. It's supposed to be a format string like `%H:%M`. – Barmar Dec 19 '19 at 04:02
  • 1
    You're not actually formatting a time, those are equivalent to `start_time = '5:00'` and `end_time = '7:00'`. What's the point of calling all the datetime functions first? – Barmar Dec 19 '19 at 04:04

1 Answers1

1

You cannot add two datetimes. Python (and most languages) differentiate between timestamps and elapsed time (duration). Operations you can do:

  • Difference between to timestamps gives you a duration
  • A timestamp plus/minus a duration gives you another timestamp
  • Arithmetic on duration: plus, subtract with another duration, multiply, divide by a constant

(Of course, in many cases in different languages, a timestamp is actually an elapsed time from a predetermined point in time, and in those cases, the two are used interchangeably, but not in this case though, unfortunately.)

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

Edited: for cases where the start time is after the end time (so that the start time is actually in the next day)


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

9mat
  • 1,194
  • 9
  • 13