Date difference in minutes in Python
How do I calculate the difference in time in minutes for the following timestamp in Python?
2010-01-01 17:31:22
2010-01-03 17:31:22
Solution 1:
minutes_diff = (datetime_end - datetime_start).total_seconds() / 60.0
Solution 2:
RSabet's answer doesn't work in cases where the dates don't have the same exact time.
Original problem:
from datetime import datetime
fmt = '%Y-%m-%d %H:%M:%S'
d1 = datetime.strptime('2010-01-01 17:31:22', fmt)
d2 = datetime.strptime('2010-01-03 17:31:22', fmt)
daysDiff = (d2-d1).days
print daysDiff
> 2
# Convert days to minutes
minutesDiff = daysDiff * 24 * 60
print minutesDiff
> 2880
d2-d1 gives you a datetime.timedelta and when you use days it will only show you the days in the timedelta. In this case it works fine, but if you would have the following.
from datetime import datetime
fmt = '%Y-%m-%d %H:%M:%S'
d1 = datetime.strptime('2010-01-01 16:31:22', fmt)
d2 = datetime.strptime('2010-01-03 20:15:14', fmt)
daysDiff = (d2-d1).days
print daysDiff
> 2
# Convert days to minutes
minutesDiff = daysDiff * 24 * 60
print minutesDiff
> 2880 # that is wrong
It would have still given you the same answer since it still returns 2 for days; it ignores the hour, min and second from the timedelta.
A better approach would be to convert the dates to a common format and then do the calculation. The easiest way to do this is to convert them to Unix timestamps. Here is the code to do that.
from datetime import datetime
import time
fmt = '%Y-%m-%d %H:%M:%S'
d1 = datetime.strptime('2010-01-01 17:31:22', fmt)
d2 = datetime.strptime('2010-01-03 20:15:14', fmt)
# Convert to Unix timestamp
d1_ts = time.mktime(d1.timetuple())
d2_ts = time.mktime(d2.timetuple())
# They are now in seconds, subtract and then divide by 60 to get minutes.
print int(d2_ts-d1_ts) / 60
> 3043 # Much better
Solution 3:
In case someone doesn't realize it, one way to do this would be to combine Christophe and RSabet's answers:
from datetime import datetime
import time
fmt = '%Y-%m-%d %H:%M:%S'
d1 = datetime.strptime('2010-01-01 17:31:22', fmt)
d2 = datetime.strptime('2010-01-03 20:15:14', fmt)
diff = d2 -d1
diff_minutes = (diff.days * 24 * 60) + (diff.seconds/60)
print(diff_minutes)
> 3043
Solution 4:
To calculate with a different time date:
from datetime import datetime
fmt = '%Y-%m-%d %H:%M:%S'
d1 = datetime.strptime('2010-01-01 16:31:22', fmt)
d2 = datetime.strptime('2010-01-03 20:15:14', fmt)
diff = d2-d1
diff_minutes = diff.seconds/60