Calculate hours, minutes between two times in Python

I’m basically a PHP developer, but there was a situation where I have to work with a Python script, you know what? I have to find hours between two times, but that was not so easy for me. Even I searched in Google a lot, I couldn’t find an easy method to calculate hours between two times in Python.

Finally, after a long time of research I got some code which helped to find days between two dates, then I sat for sometime and wrote a script which gives hours minutes and seconds between two dates.

Here is the script:

from datetime import datetime

#set the date and time format
date_format = "%m-%d-%Y %H:%M:%S"

#convert string to actual date and time
time1  = datetime.strptime('8-01-2008 00:00:00', date_format)
time2  = datetime.strptime('8-02-2008 01:30:00', date_format)

#find the difference between two dates
diff = time2 - time1


''' days and overall hours between two dates '''
print ('Days & Overall hours from the above two dates')
#print days
days = diff.days
print (str(days) + ' day(s)')

#print overall hours
days_to_hours = days * 24
diff_btw_two_times = (diff.seconds) / 3600
overall_hours = days_to_hours + diff_btw_two_times
print (str(overall_hours) + ' hours');



''' now print only the time difference '''
''' between two times (date is ignored) '''

print ('\nTime difference between two times (date is not considered)')

#like days there is no hours in python
#but it has seconds, finding hours from seconds is easy
#just divide it by 3600

hours = (diff.seconds) / 3600  
print (str(hours) + ' Hours')


#same for minutes just divide the seconds by 60

minutes = (diff.seconds) / 60
print (str(minutes) + ' Minutes')

#to print seconds, you know already ;)

print (str(diff.seconds) + ' secs')

Read the comments in the program to understand it.

Enjoy the day.

1 thought on “Calculate hours, minutes between two times in Python”

  1. Jonathan Hernandez

    >>> import datetime
    >>>
    >>> d1 = datetime.datetime(2014,11,1,23,59,59)
    >>> d2 = datetime.datetime(2014,11,10,20,0,9)
    >>>
    >>> (d2-d1).total_seconds()/60/60 # hours
    212.00277777777777
    >>>

    😀

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top