When working with dates and times in Python, you'll often need to calculate the time difference. In this tutorial, you'll learn how to calculate the difference between two timestamps in hours, minutes, and seconds.

By the end of this tutorial, you'll have learned:

  • how to use Python's datetime module to work with dates and time,
  • what timedelta objects are, and how they're useful, and
  • calculate the time difference between any two timestamps—in hours, minutes, and seconds.

Let's get started.

How to use Python's datetime module

To work with dates and times in Python, you'll use the datetime module. The datetime module is part of the Python standard library. So you can go ahead and import it into your working environment right away, like this:

import datetime

In order to calculate the time difference, you need to create two different timestamps. You can choose to create:

  • two date objects,
  • two time objects, or
  • a combination of both date and timedatetime objects.

How to create a date object in Python

Let's import the date class from datetime module. To create a date object in Python, you can use the general syntax datetime.date(<year>,<month>,<day>). Here's an example of creating a date object date1:

from datetime import date
date1 = datetime.date(2022,3,27)
print(date1)

# Output: 2022-03-27

You can try the code on the Geekflare Python compiler to test. Or, install Python on your computer.

As shown above, when you print the date, it's formatted in the YYYY-MM-DD format for dates.

Note: Be sure to specify the month as an integer without any leading zeros. It's likely you're used to adding a leading zero to the month when writing down dates.

For example, to specify a date in June, the 6th month of the year: use 6 and not 06.

For example, try running the following code snippet—where the month has been mentioned as 03 instead of just 3. You'll see that it throws a Syntax Error as shown:

date1 = datetime.date(2022,03,27)

print(date1)

# Error Message
File "<ipython-input-12-6eb72084e6ce>", line 1
    date1 = datetime.date(2022,03,27)
                                ^
SyntaxError: invalid token

Let's now see how to create a time object in Python.

How to create a time object in Python

To create a time object, let's import the time class. Any Python time object can be created using the time class by specifying the following class attributes: hour, minute, second, and microsecond.

However, all of these attributes are optional. If you don't specify a certain attribute, say, second, it's set to 0 by default.

The following code snippet shows how you can create a time object time1. As with the date object, you can print out the time object to see the formatted time.

from datetime import time
time1 = datetime.time(13,27,45,4600)
print(time1)

# Output: 13:27:45.004600

How to create a datetime object in Python

As you can see, the date object has no information about the time. And the time object doesn't contain information about the date.

However, in practice, you'll need both the date and time information. So it's recommended to use the datetime class instead.

You can access the datetime class and create datetime objects in Python, as shown below:

dt1 = datetime.datetime(2022,3,27,13,27,45,46000)
print(dt1)

# Output: 2022-03-27 13:27:45.046000

Let's now create another datetime object dt2 without the second attribute. You can see that it's set to 0 – the default value.

dt2 = datetime.datetime(2022,6,30,14,28)
print(dt2)

# Output: 2022-06-30 14:28:00

So far you've learned how to create timestamps in Python—as dates, times, and datetimes. It's now time to see how you can calculate the difference between any two timestamps.

Head over to the next section to find out.

How to use timedelta object in Python

In Python, timedelta denotes a span of time. It's the difference between two date, time, or datetime objects.

If you add or subtract two date, time, or datetime objects, you'll get a timedelta object. This timedelta object has useful attributes and methods that can help calculate the time difference.

Let's go ahead and calculate the difference between the two datetime objects dt1 and dt2.

dt1 = datetime.datetime(2022,3,27,13,27,45,46000) 
dt2 = datetime.datetime(2022,6,30,14,28) 
tdelta = dt2 - dt1 
print(tdelta) 
print(type(tdelta)) 

# Output 
95 days, 1:00:14.954000 
<class 'datetime.timedelta'>

From the above code snippet, you can see that the tdelta variable holds the time difference between dt1 and dt2. And the type of tdelta is verified to be of the class timedelta using Python's built-in type() function.

Now let's code another example.

How to find time difference between two dates

Let's take a simple yet interesting example.

Problem: To calculate the time difference between the current date (today) and your birthday.
To do this, set today as the first timestamp, and your birthday as the second timestamp.

As a first step, let's create two datetime objects:

  • one for today, let's call it today, and
  • another for your birthday, let's call it bday

The datetime class has the now() method that gives you the current local date and time. So let's use it get today—our reference date.

today = datetime.datetime.now()
print(today)

# Sample Output: 2022-01-22 09:10:18.489538

In the code below, replace bday with your birthday to calculate the time left for your birthday this year.

If you're reading this after your birthday has passed, feel free to set bday to your next birthday.

bday = datetime.datetime(2022,8,30,11,59)
print(bday)

# Sample Output: 2022-08-30 11:59:00

The next step is to calculate time_diff which is a timedleta object, as explained earlier. Simply subtract today from your bday, and you'll have the time difference.

time_diff = bday - today
print(f"Your birthday is in {time_diff}")

# Output
Your birthday is in 220 days, 2:46:00.127416

To know the number of days left, use the days attribute on time_diff, as shown:

tdays = time_diff.days
print(f"Your birthday is in {tdays} days.")

# Output
Your birthday is in 220 days.

How to find time difference in seconds

Let's now calculate how many seconds away your birthday is.

To calculate the total time difference in seconds, use the total_seconds() method on the timedelta object time_diff.

tsecs = time_diff.total_seconds()
print(f"Your birthday is {tsecs} seconds away.")

# Output
Your birthday is 19017960.127416 seconds away.

Well, that's too long a wait!

That said, you now know how to calculate the time difference between any two timestamps in seconds.

Let's now revisit some basics and write down the following. A day is composed of 24 hours, an hour is 60 minutes long, and 60 seconds make up a minute.

This is summarized in the image below:

Hours, Minutes, and Seconds

So to convert from seconds to minutes, hours and days, you can use the following table, and divide by the corresponding conversion factor.

Time Conversion Table

In the next sections, let's convert the time difference in seconds to minutes and hours.

How to find time difference in minutes

To get the time difference in minutes, you only need to divide the total seconds by 60.

Let's divide tsecs by 60, and store it in a variable called tmins, like this:

tmins = tsecs/60
print(f"Your birthday is {tmins} minutes away.")

# Output
Your birthday is 316966.0021236 minutes away.

How to find time difference in hours

Now that you've calculated the time difference in minutes, you can divide that by a factor of 60 to get the difference in hours. Or you could divide the total seconds by 60*60 = 3600.

thrs = tsecs/(60*60)
print(f"Your birthday is {thrs} hours away.")

# Output
Your birthday is 5282.76670206 hours away.

So you've now learned how to calculate the time difference in any unit of your choice.

Conclusion

In this tutorial, you've learned how to:

  • create and work with dates and times using Python's datetime module,
  • use timedelta objects to get a span of time, or time difference, and
  • calculate the time difference in seconds, minutes, and hours.

Hope you found this tutorial helpful. Now that you know all about calculating time difference in Python, it's time to put your skills to practice.

Happy learning and coding!

Learn how to write equal to or not equal to code or  make a snake game in python here.