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:
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 time—datetime 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)
# Output: 2022-03-27
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.
Bala Priya is a developer and technical writer from India with over three years of experience in the technical content writing space. She shares her learning with the developer community by authoring tech tutorials, how-to guides, and more…. read more
Python is a very versatile language, and Python developers often have to work with a variety of files and get information stored in them for processing. One popular file format you’re bound to encounter as a Python developer is the Portable Document Format popularly known as PDF