How to calculate the time difference between two times in minutes in Python
Hello! In this article, we will calculate the time difference in minutes using Python.
Python has a library called datetime to work with the date and time. We will be using the datetime library to calculate the time difference.
Python program to calculate time difference in minutes
First of all, we will import the datetime module into our program.
The datetime module consists of datetime class which helps us to work with the date and time. We will initialize the datetime object by passing the data to its constructor.
The data includes the year, month, day, hour, minute, second, microsecond and tzinfo. Out of which year, month and day are mandatory. The attribute tzinfo is used to know the time zone details. By default, it uses the current system’s time zone. Its default value is None.
Syntax – datetime( year, month, day, hour, minute, second, microsecond, tzinfo)
We will provide the initial date and time in our program using the datetime( ) constructor.
Now, we will find the current date and time in our program using datetime.now( ) method.
Calculate the difference between these d1 and d2 objects which returns timedelta object.
Finally, fetch the seconds using total_seconds( ) method. Convert that seconds into minutes by dividing it by 60 and print the result.
import datetime d1=datetime.datetime(2022,1,18,0,0,0) d2=datetime.datetime.now() diff=d2-d1 print(diff.total_seconds()/(60))
That’s it! Hope you learned how to calculate time difference in minutes using Python. Here are some other related articles to check out.