Python difference between two times – How to Calculate the Time Difference Between Two Times in Minutes in Python?

Python difference between two times: To work with dates and times, Python includes a module called datetime. To compute the time difference, we will use the datetime library.

datetime module:

Time difference python: The datetime module includes the datetime class, which allows us to work with dates and times. Initialize the datetime object by passing the data to its constructor.

Synatx:

 datetime( year, month, day, hour, minute, second, microsecond, tzinfo)

Parameters

year: This is required. It is the year given as input.

month: This is required. It is the month given as input.

day: This is required. It is the month given as input.

hour: This is optional. It is the hour given as input.

second: This is optional. It is the second given as input.

microsecond: This is optional. It is the microsecond given as input.

tzinfo: The argument tzinfo is used to obtain time zone information. It uses the current system’s time zone by default. It has the default value of None.

Calculating the Time Difference Between Two Times in Minutes in Python

Example

Approach:

  • Import datetime module using the import keyword.
  • Pass some random year, month, day, hour, minute, second as arguments to the datetime() function of the datetime module to get the given date and time of the year
  • Store it in a variable
  • Get the current date and time using the datetime.now() function
  • Store it in another variable
  • Calculate the difference between the dates and Store it in a variable
  • Apply total_seconds() function on the above differnce obtained to convert the date difference into seconds and divide the result by 60 to convert it into minutes and print it.
  • Here total_seconds()/(60) gives the difference between two dates in minutes.
  • The Exit of the Program.

Below is the implementation:

# Import datetime module using the import keyword.
import datetime
# Pass some random year, month, day, hour, minute, second as arguments to the 
# datetime() function of the datetime module to get the given date and time of the year
# Store it in a variable
gvn_date = datetime.datetime(2020, 3, 14, 5, 15, 0)
# Get the current date and time using the datetime.now() function
# Store it in another variable
current_date =datetime.datetime.now()
# Calculate the difference between the dates and Store it in a variable
rslt_diffence = current_date - gvn_date
# Apply total_seconds() function on the above differnce obtained to convert the
# date difference into seconds and divide the result by 60 to convert it into minutes
# and print it.
# Here total_seconds()/(60) gives the difference between two dates in minutes.
print("The difference between two dates in minutes:")
print(rslt_diffence.total_seconds()/(60))

Output:

The difference between two dates in minutes:
1045958.5962696166