Python : Comparing two times, and returning in minutes
12,953
You function needs to return
newTime
:
import datetime
def timeDiff(time1,time2):
timeA = datetime.datetime.strptime(time1, "%H:%M")
timeB = datetime.datetime.strptime(time2, "%H:%M")
newTime = timeA - timeB
return newTime.seconds/60
print timeDiff('15:59','15:53'), 'minutes'
>>> 6 minutes
Notes:
I think you want newTime = timeB - timeA
otherwise you have to pass the times in backwards like I did.
Author by
Muhammed Bhikha
Updated on November 23, 2022Comments
-
Muhammed Bhikha over 1 year
I have a method which takes two strings (times) e.g.
15:01
The method should take the times and dotime1-time2
and return to me a new time in minutes. eg.15:53 - 15:59
should give me6 minutes
however i'm stuck.This is my code:
import datetime class timeCalc(object): def timeDiff(self,time1,time2): timeA = datetime.datetime.strptime(time1, "%H:%M") timeB = datetime.datetime.strptime(time2, "%H:%M") newTime = timeA - timeB
-
Daniel Roseman over 11 yearsWhy are you stuck? What does
newTime
give you? What happens when you explore the methods available on that object? (And why are you defining a class here - why isn'ttimeDiff
just a function?) -
Muhammed Bhikha over 11 yearsit gives me the result in a very weird format. I want the difference in minutes, then when I go to print in the console, it throws up an error
-
-
olofom over 11 yearsTo get the answer in minutes you should return
newTime.seconds/60
instead. -
Chris Seymour over 11 yearsThanks @olofom added it to my answer +1