Open In App

Date difference in minutes in Python

Last Updated : 03 May, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

To calculate the date difference in minutes in Python, subtract two datetime objects to get the time difference. Then, convert that difference into minutes or break it down into minutes and seconds based on your needs. For example: for two dates, 2025-05-03 18:45:00 and 2025-05-03 16:30:00, the time difference is 2 hours and 15 minutes, which equals 135 minutes.

Using total_seconds()

This method offering a quick and efficient way to obtain a single numeric value representing the entire duration. It’s particularly useful when you want to convert the time gap into minutes, hours or days as needed.

Python
from datetime import datetime

a = datetime(2017, 6, 21, 18, 25, 30)
b = datetime(2017, 5, 16, 8, 21, 10)
res = int((a - b).total_seconds() // 60)
print(res)

Output
52444

Explanation:

  • a and b are datetime objects for June 21, 2017, 18:25:30 and May 16, 2017, 08:21:10.
  • a - b gives a timedelta object representing their difference.
  • .total_seconds() returns the total difference in seconds.
  • int(... // 60) converts it into whole minutes.

Using divmod()

divmod() function is useful for breaking down seconds into minutes and remaining seconds by returning both the quotient and remainder in a single step. It's ideal for producing more human-readable results, such as "X minutes and Y seconds."

Python
from datetime import datetime

a = datetime(2017, 6, 21, 18, 25, 30) 
b = datetime(2017, 5, 16, 8, 21, 10)   
ts = (a - b).total_seconds()  # total seconds difference

m, s = divmod(ts, 60) 
print("{} minutes and {} seconds".format(int(m), int(s))) 

Output
52444 minutes and 20 seconds

Explanation:

  • a and b are datetime objects for June 21, 2017, 18:25:30 and May 16, 2017, 08:21:10.
  • (a - b).total_seconds() calculates the time difference between a and b, converting it into total seconds.
  • divmod(ts, 60) divides total seconds ts by 60 to get minutes m and remaining seconds s .

Using manual calculation via days and seconds

This method directly accesses the .days and .seconds attributes of the timedelta object to manually compute the total time difference. By multiplying the number of days by 1440 (the number of minutes in a day) and adding the remaining seconds converted to minutes, you get the full duration in minutes.

Python
from datetime import datetime

a = datetime(2025, 5, 3, 18, 45, 0)  
b = datetime(2025, 5, 3, 16, 30, 0)  

d = a - b  # Time difference
m = d.days * 1440 + d.seconds // 60  # Total minutes
print(m) 

Output
135

Explanation:

  • a and b are datetime objects representing specific timestamps on May 3, 2025 at 18:45 and 16:30 respectively.
  • d.days * 1440 converts days to minutes (1440 minutes per day).
  • d.seconds // 60 converts remaining seconds into minutes.

Next Article

Similar Reads