Calculate Number of Hours, Minutes & Seconds Between Two datetimes in Python (3 Examples)

 

In this article you’ll learn how to compute the number of hours, minutes, and seconds between two dates and times using the Python programming language.

Our table of content is structured as shown below:

Let’s dive right into it!

 

Add-On Libraries

As a first step, we have to import the datetime module and relativedelta from the dateutil module:

import datetime
from dateutil import relativedelta

 

Example 1: Calculate the Difference Between Two Dates in Hours, Minutes & Seconds Format

Then, let’s construct some example datetime objects for our example:

datetime_1 = datetime.datetime(1999, 10, 25, 19, 3, 16)
datetime_2 = datetime.datetime(1999, 6, 1, 9, 12, 7)

Afterwards, we will set the difference between the dates to a timedelta object by simply using the minus sign.

Note: The following if else statement can be used to avoid negative difference results due to dates being unknown in the program initially.

if datetime_1 < datetime_2:
    diff = datetime_2 - datetime_1
else:
    diff = datetime_1 - datetime_2

The subtraction operation between two datetime objects returns a timedelta object.

print(type(diff)) # <class 'datetime.timedelta'>

A timedelta object has the following fields and functions for use:

print("No. of Total Seconds:", diff.total_seconds()) # Total difference in seconds
 
print("No. of Days:", diff.days)                 # Number of days between the datetimes
print("No. of Seconds:", diff.seconds)           # Number of seconds in the remainder 
print("No. of Microseconds:", diff.microseconds) # Number of microseconds in the remainder
 
# of Total Seconds: 12649869.0
# of Days: 146
# of Seconds: 35469
# of Microseconds: 0

If you still have doubts about the timedelta object fields, you can use the following line to ease your mind (of course this is only true if there are microsecond differences between datetimes).

print("Are they the same?", 
      (diff.total_seconds() - diff.days * 24 * 60 * 60) == diff.seconds)
# Are they the same? True

Although the timedelta library provides the basic units, we may need more types of units. In order to achieve this, we can do the following:

First let’s set our desired time units in terms of seconds. In this example we will focus on hours, minutes, and seconds.

minute  = 60
hour    = minute * 60

We will use the built-in function divmod for the next part. It’s a function which divides the first parameter with the second parameter and returns a tuple: (quotient, remainder).

hours   = divmod(diff.total_seconds(), hour)   # Calculate the amount of full hours
minutes = divmod(hours[1], minute)             # Divide remainder to find minutes
seconds = minutes[1]                           # Divide remainder to find seconds
 
print("Time difference: %d hours, %d minutes and %d seconds"
      % (hours[0], minutes[0], seconds))
# Time difference between dates: 3513 hours, 51 minutes and 9 seconds

 

Example 2: Difference in Weeks & Days

This example explains how to get the time difference in weeks and days using the same dates as in Example 1.

Similar to the previous example, we will get the difference, set our time units, and calculate the amounts corresponding to each time unit.

datetime_1 = datetime.datetime(1999, 10, 25, 19, 3, 16)
datetime_2 = datetime.datetime(1999, 6, 1, 9, 12, 7)
 
if datetime_1 < datetime_2:
    diff = datetime_2 - datetime_1
else:
    diff = datetime_1 - datetime_2
 
minute  = 60
hour    = minute * 60
day     = hour * 24
week    = day * 7
 
weeks   = divmod(diff.total_seconds(), week)    # Calculate the amount of full weeks
days    = divmod(weeks[1], day)                 # Divide remainder to find days
hours   = divmod(days[1], hour)                 # Divide remainder to find hours
minutes = divmod(hours[1], minute)              # Divide remainder to find minutes
seconds = minutes[1]                            # Divide remainder to find seconds
 
 
print("Time difference: %d weeks, %d days, %d hours, %d minutes and %d seconds"
      % (weeks[0], days[0], hours[0], minutes[0], seconds))
# Time difference: 20 weeks, 6 days, 9 hours, 51 minutes and 9 seconds

The previous two examples were solved with a more hands-on approach to the problem, and it is problematic for months because the day count varies throughout the months, which brings us to our final example.

Example 3: Using relativedelta Library

In this example we will use a library which automatically partitions the time starting from years until seconds. If you need a full scope of standard time units, this is the most practical method.

Note: Even though relativedelta has a weeks field as well, it’s only for operations between relativedelta objects and can’t be used for this example.

datetime_1 = datetime.datetime(1999, 10, 25, 19, 3, 16)
datetime_2 = datetime.datetime(1999, 6, 1, 9, 12, 7)
 
if datetime_1 < datetime_2:
    diff = relativedelta.relativedelta(datetime_2, datetime_1)
else:
    diff = relativedelta.relativedelta(datetime_1, datetime_2)
 
years   = diff.years
months  = diff.months
days    = diff.days
hours   = diff.hours
minutes = diff.minutes
seconds = diff.seconds
 
print("Time difference: %d years %d months %d days %d hours %d minutes %d seconds"
      % (years, months, days, hours, minutes, seconds))
# Time difference: 0 years 4 months 24 days 24 hours 51 minutes 9 seconds

The tutorial where the relativedelta library is used to calculate the difference in terms of days, months, and years can be found in the list of tutorials below.

 

Video, Further Resources & Summary

In case you need more examples and explanations on how to get time differences using Python, you should have a look at the following YouTube video of the Statistics Globe YouTube channel.

 

The YouTube video will be added soon.

 

Furthermore, you might have a look at some of the related tutorials on the Statistics Globe website:

This article has shown how to get the time difference between two dates in hours, minutes, and seconds. In case you have any additional questions, you might leave a comment below.

 

Ömer Ekiz Informatics Expert

This page was created in collaboration with Ömer Ekiz. You may have a look at Ömer’s author page to read more about his academic background and the other articles he has written for Statistics Globe.

 

Subscribe to the Statistics Globe Newsletter

Get regular updates on the latest tutorials, offers & news at Statistics Globe.
I hate spam & you may opt out anytime: Privacy Policy.


Leave a Reply

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

Fill out this field
Fill out this field
Please enter a valid email address.

Top