How to get duration between two dates in hours, minutes and seconds with Python

1 Answer

0 votes
from datetime import datetime

def get_duration(duration):
    hours = int(duration / 3600)
    minutes = int(duration % 3600 / 60)
    seconds = int((duration % 3600) % 60)
    return '{:02d}:{:02d}:{:02d}'.format(hours, minutes, seconds)

date_format = '%Y-%m-%d %H:%M:%S'
str_start_date = '2022-03-01 12:05:00'
str_end_date = '2022-03-02 10:12:30'

start_date = datetime.strptime(str_start_date, date_format)
end_date = datetime.strptime(str_end_date, date_format)

duration = (end_date - start_date).total_seconds()

print(get_duration(duration))

   
   
   
'''
run:
   
22:07:30
   
'''

 



answered Mar 2, 2022 by avibootz
...