Python | Difference between two dates (in minutes) using datetime.timedelta() method

To find the difference between two dates in Python, one can use the timedelta class which is present in the datetime library. The timedelta class stores the difference between two datetime objects.
To find the difference between two dates in form of minutes, the attribute seconds of timedelta object can be used which can be further divided by 60 to convert to minutes.

Example 1:

The following program takes two datetime objects and finds the difference between them in minutes.



filter_none

edit
close

play_arrow

link
brightness_4
code

import datetime
  
# datetime(year, month, day, hour, minute, second)
a = datetime.datetime(2017, 6, 21, 18, 25, 30)
b = datetime.datetime(2017, 5, 16, 8, 21, 10)
  
# returns a timedelta object
c = a-
print('Difference: ', c)
  
minutes = c.seconds / 60
print('Difference in minutes: ', minutes)

chevron_right


Output:

Difference:  36 days, 10:04:20
Difference in minutes:  604.3333333333334

 
Example 2:
To get a more appropriate answer divmod() can be used which will return the fractional part of the minutes in terms of seconds:

filter_none

edit
close

play_arrow

link
brightness_4
code

import datetime
  
# datetime(year, month, day, hour, minute, second)
a = datetime.datetime(2017, 6, 21, 18, 25, 30)
b = datetime.datetime(2017, 5, 16, 8, 21, 10)
  
# returns a timedelta object
c = a-
print('Difference: ', c)
  
# returns (minutes, seconds)
minutes = divmod(c.seconds, 60
print('Difference in minutes: ', minutes[0], 'minutes',
                                 minutes[1], 'seconds')

chevron_right


Output:

Difference:  36 days, 10:04:20
Difference in minutes:  604 minutes 20 seconds


My Personal Notes arrow_drop_up


If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.