Reputation: 39
I have two timestamps:
time1= "2020-01-25T01:47:35.431Z"
time2="2020-01-25T02:02:57.500Z"
I used the following function to calculate the time interval between the two and return it in minute and round to two decimals.
def app_run2_min_diff(time1,time2):
time1= str(time1)
time1datetime.strptime(time1,'%Y-%m-%dT%H:%M:%S.%fZ')
time2= str(time2)
time2=datetime.strptime(time2,'%Y-%m-%dT%H:%M:%S.%fZ')
sec1=time1.strftime('%S')
sec2=time2.strftime('%S')
min_dif=round((float(sec2)-float(sec1)/60),2)
return min_dif
My logic is that to deduct the second difference first and then convert to minute. The min_dff I got is 34.42 , but the correct answer is 15.35. What's wrong with my logic above?
Upvotes: 0
Views: 1085
Reputation: 2692
The easier way to do would be to convert datetime.strptime
object to datetime.timedelta
by simply subtracting two dates. Then applying simple arithmetic will give you the reuslt.
from datetime import datetime
time1= "2020-01-25T01:47:35.431Z"
time2="2020-01-25T02:02:57.500Z"
def to_minutes(td):
return td.days*1440 + td.seconds/60
def app_run2_min_diff(time1,time2):
time1 = datetime.strptime(time1,'%Y-%m-%dT%H:%M:%S.%fZ')
time2 = datetime.strptime(time2,'%Y-%m-%dT%H:%M:%S.%fZ')
time_diff = time2 - time1
min_dif = round(to_minutes(time_diff), 2)
return min_dif
The result of app_run2_min_diff(time1, time2)
will be:
15.37
Upvotes: 2