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.

Share:
12,953
Muhammed Bhikha
Author by

Muhammed Bhikha

Updated on November 23, 2022

Comments

  • Muhammed Bhikha
    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 do time1-time2 and return to me a new time in minutes. eg. 15:53 - 15:59 should give me 6 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
      Daniel Roseman over 11 years
      Why 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't timeDiff just a function?)
    • Muhammed Bhikha
      Muhammed Bhikha over 11 years
      it 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
    olofom over 11 years
    To get the answer in minutes you should return newTime.seconds/60 instead.
  • Chris Seymour
    Chris Seymour over 11 years
    Thanks @olofom added it to my answer +1