Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python finding difference between two time stamps in minutes

How i can find the difference between two time stamps in minutes . for example:-

timestamp1=2016-04-06 21:26:27
timestamp2=2016-04-07 09:06:02
difference = timestamp2-timestamp1
= 700 minutes (approx)
like image 343
Shubham Jairath Avatar asked Apr 07 '16 15:04

Shubham Jairath


People also ask

How do you find the difference between two timestamps in Python?

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.

How do you find the difference between two timestamps in minutes?

Discussion: If you'd like to calculate the difference between the timestamps in seconds, multiply the decimal difference in days by the number of seconds in a day, which equals 24 * 60 * 60 = 86400 , or the product of the number of hours in a day, the number of minutes in an hour, and the number of seconds in a minute.


1 Answers

Using the datetime module:

from datetime import datetime

fmt = '%Y-%m-%d %H:%M:%S'
tstamp1 = datetime.strptime('2016-04-06 21:26:27', fmt)
tstamp2 = datetime.strptime('2016-04-07 09:06:02', fmt)

if tstamp1 > tstamp2:
    td = tstamp1 - tstamp2
else:
    td = tstamp2 - tstamp1
td_mins = int(round(td.total_seconds() / 60))

print('The difference is approx. %s minutes' % td_mins)

Output is:

The difference is approx. 700 minutes
like image 106
dron22 Avatar answered Oct 03 '22 23:10

dron22