m_sasha
m_sasha

Reputation: 269

How to find the average time between two datetimes.datetime?

I have two times (hours minutes in datetime format, 1 hour 30 minutes and 2 hours 50 minutes respectively)

min_time = datetime.datetime(1900, 1, 1, 1, 30)
max_time = datetime.datetime(1900, 1, 1, 2, 5)

I need to get the middle time between this interval 1:30 < {2:10} < 2:50

How can this be implemented in code with the datetime module?: max_time - min_time / 2 + min_time = 2:10?

Upvotes: 2

Views: 800

Answers (1)

Cameron Riddell
Cameron Riddell

Reputation: 13407

Your formula worked pretty well for me. If you're not interested in the year you can ignore it or format it out when displaying.

import datetime

min_time = datetime.datetime(1900, 1, 1, 1, 30)
max_time = datetime.datetime(1900, 1, 1, 2, 50)
mid_time = ((max_time - min_time) / 2) + min_time

print(
    mid_time,                   # 1900-01-01 02:10:00
    mid_time.strftime('%H:%M'), # 02:10
    sep='\n'
)

Upvotes: 2

Related Questions