Examples of how to find the difference in minutes between two dates in python:
1 -- Create two dates
Let's create two dates objects in python using the module datetime:
import datetimeyear = 2008month = 7day = 8hour = 12minute = 47second = 0time1 = datetime.datetime(year,month,day,hour,minute,second)hour = 14minute = 20time2 = datetime.datetime(year,month,day,hour,minute,second)
2 -- Example 1 using total_seconds() function:
A solution is to then calculate the difference
time_delta = time2 - time1
and to extract the difference in seconds using total_seconds():
delta_in_seconds = time_delta.total_seconds()print(delta_in_seconds)5580.0
that can be converted in minutes (since 1 minute = 60 seconds):
delta_in_minutes = delta_in_seconds / 60.print(delta_in_minutes)
which returns here:
93.0
minutes difference between the two dates.
3 -- Exemple 2
Another example:
delta_in_seconds = time_delta.secondsprint(delta_in_seconds)delta_in_minutes = delta_in_seconds / 60.print(delta_in_minutes)
4 -- Fraction of a minute
In the case the difference in minutes between the two dates is not an integer, a solution is to use divmod():
hour = 14minute = 20second = 25time2 = datetime.datetime(year,month,day,hour,minute,second)time_delta = time2 - time1delta_in_seconds = time_delta.total_seconds()delta_in_minutes = divmod(delta_in_seconds, 60)print(delta_in_minutes)print('Time difference : {} minutes and {} seconds'.format(delta_in_minutes[0],delta_in_minutes[1]))
returns
(93.0, 25.0)Time difference : 93.0 minutes and 25.0 seconds
