How to Calculate Time Difference in Python

When running with dates and occasions in Python, you’ll continuously want to calculate the time distinction. In this instructional, you’ll learn the way to calculate the variation between two timestamps in hours, mins, and seconds.

By the tip of this instructional, you’ll have realized:

  • how to use Python’s datetime module to paintings with dates and time,
  • what timedelta items are, and the way they’re helpful, and
  • calculate the time distinction between any two timestamps—in hours, mins, and seconds.

Let’s get began.

How to use Python’s datetime module

To paintings with dates and occasions in Python, you’ll use the datetime module. The datetime module is a part of the Python same old library. So you’ll be able to pass forward and import it into your running atmosphere straight away, like this:

import datetime

In order to calculate the time distinction, you wish to have to create two other timestamps. You can make a selection to create:

  • two date items,
  • two time items, or
  • a mixture of each date and timedatetime items.

How to create a date object in Python

Let’s import the date elegance from datetime module. To create a date object in Python, you’ll be able to use the overall syntax<yr>,<month>,<day>). Here’s an instance of constructing a date object date1:

from datetime import date
date1 =,3,27)

# Output: 2022-03-27

You can check out the code at the Geekflare Python compiler to check. Or, set up Python to your pc.

As proven above, whilst you print the date, it’s formatted in the YYYY-MM-DD structure for dates.

Note: Be positive to specify the month as an integer with out any main zeros. It’s most probably you’re used to including a number one 0 to the month when writing down dates.

For instance, to specify a date in June, the sixth month of the yr: use 6 and no longer 06.

For instance, check out operating the next code snippet—the place the month has been discussed as 03 as an alternative of simply 3. You’ll see that it throws a Syntax Error as proven:

date1 =,03,27)


# Error Message
File "<ipython-input-12-6eb72084e6ce>", line 1
    date1 =,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 elegance. Any Python time object may also be created the use of the time elegance by way of specifying the next elegance attributes: hour, minute, 2d, and microsecond.

However, all of those attributes are not obligatory. If you don’t specify a undeniable characteristic, say, 2d, it’s set to 0 by way of default.

The following code snippet displays how you’ll be able to create a time object time1. As with the date object, you’ll be able to print out the time object to see the formatted time.

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

# Output: 13:27:45.004600

How to create a datetime object in Python

As you’ll be able to see, the date object has no details about the time. And the time object doesn’t comprise details about the date.

However, in observe, you’ll want each the date and time knowledge. So it’s really useful to use the datetime elegance as an alternative.

You can get entry to the datetime elegance and create datetime items in Python, as proven beneath:

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

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

Let’s now create every other datetime object dt2 with out the 2d characteristic. You can see that it’s set to 0 – the default price.

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

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

So a long way you’ve realized how to create timestamps in Python—as dates, occasions, and datetimes. It’s now time to see how you’ll be able to calculate the variation between any two timestamps.

Head over to the following segment to to find out.

How to use timedelta object in Python

In Python, timedelta denotes a span of time. It’s the variation between two date, time, or datetime items.

If you upload or subtract two date, time, or datetime items, you’ll get a timedelta object. This timedelta object has helpful attributes and techniques that may assist calculate the time distinction.

Let’s pass forward and calculate the variation between the 2 datetime items dt1 and dt2.

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

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

From the above code snippet, you’ll be able to see that the tdelta variable holds the time distinction between dt1 and dt2. And the kind of tdelta is verified to be of the category timedelta the use of Python’s built-in type() serve as.

Now let’s code every other instance.

How to to find time distinction between two dates

Let’s take a easy but attention-grabbing instance.

Problem: To calculate the time distinction between the present date (these days) and your birthday.
To do that, set these days as the primary timestamp, and your birthday as the second one timestamp.

As a primary step, let’s create two datetime items:

  • one for these days, let’s name it these days, and
  • every other on your birthday, let’s name it bday

The datetime elegance has the now() approach that will give you the present native date and time. So let’s use it get these days—our reference date.

these days =
print(these days)

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

In the code beneath, substitute bday together with your birthday to calculate the time left on your birthday this yr.

If you’re reading this after your birthday has handed, be happy to set bday to your subsequent birthday.

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

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

The subsequent step is to calculate time_diff which is a timedleta object, as defined previous. Simply subtract these days out of your bday, and also you’ll have the time distinction.

time_diff = bday - these days
print(f"Your birthday is in time_diff")

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

To know the selection of days left, use the times characteristic on time_diff, as proven:

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

# Output
Your birthday is in 220 days.

How to to find time distinction in seconds

Let’s now calculate what number of seconds away your birthday is.

To calculate the whole time distinction in seconds, use the total_seconds() approach at 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 lengthy a wait!

That mentioned, you presently know the way to calculate the time distinction between any two timestamps in seconds.

Let’s now revisit some fundamentals and write down the next. An afternoon consists of 24 hours, an hour is 60 mins lengthy, and 60 seconds make up a minute.

This is summarized in the picture beneath:

Hours, Minutes, and Seconds

So to convert from seconds to mins, hours and days, you’ll be able to use the next desk, and divide by way of the corresponding conversion issue.

Time Conversion Table

In the following sections, let’s convert the time distinction in seconds to mins and hours.

How to to find time distinction in mins

To get the time distinction in mins, you handiest want to divide the whole seconds by way of 60.

Let’s divide tsecs by way of 60, and retailer it in a variable referred to as tmins, like this:

tmins = tsecs/60
print(f"Your birthday is tmins mins away.")

# Output
Your birthday is 316966.0021236 mins away.

How to to find time distinction in hours

Now that you just’ve calculated the time distinction in mins, you’ll be able to divide that by way of an element of 60 to get the variation in hours. Or you want to divide the whole seconds by way of 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 realized how to calculate the time distinction in any unit of your selection.


In this instructional, you’ve realized how to:

  • create and paintings with dates and occasions the use of Python’s datetime module,
  • use timedelta items to get a span of time, or time distinction, and
  • calculate the time distinction in seconds, mins, and hours.

Hope you discovered this instructional useful. Now that you realize all about calculating time distinction in Python, it’s time to put your talents to observe.

Happy finding out and coding!

Related Articles

Leave a Reply

Your email address will not be published.

Back to top button