## Wednesday, December 18, 2019

### Python Program to Find the Difference between two Times.

#### Python Program to Find the Difference between two Times.

Python program to find the difference between two times.

0. Import datetime module.

We'll use datetime.strptime ( ) function to create time objects. Then we'll calculate the difference between them. Also, we'll use datetime.strftime ( ) function to convert time object to string of required format.

from datetime import datetime

1. init ( ) - Get two times.

class TimeDifference: ''' Calculate difference between two times ''' def __init__(self, time1, time2): self.time1 = time1 self.time2 = time2 self.diff = None

2. get_difference ( ) - Find the difference between two times.

def get_difference(self):
''' Get the difference between two times ''' self.diff = abs(self.time1 - self.time2) t1 = self.time1.strftime('%H:%M:%S') t2 = self.time2.strftime('%H:%M:%S') print(f'Difference between {t1} and {t2} is {self.diff.seconds} seconds')

3. main ( ) - Driver code to test the program.

def main(): ''' Take two dates and find the difference between them ''' # use datetime.strptime() function to create time object # pass string in this format %H:%M:%S # H is Hour, M is Minute and S is Second time_format = '%H:%M:%S' time1 = datetime.strptime('12:45:01', time_format) time2 = datetime.strptime('11:30:00', time_format) time_diff = TimeDifference(time1, time2) time_diff.get_difference() if __name__ == '__main__':
main()

#### Complete Code - time_difference.py

from datetime import datetime class TimeDifference: ''' Calculate difference between two times ''' def __init__(self, time1, time2): self.time1 = time1 self.time2 = time2 self.diff = None def get_difference(self): ''' Get the difference between two times ''' self.diff = abs(self.time1 - self.time2) t1 = self.time1.strftime('%H:%M:%S') t2 = self.time2.strftime('%H:%M:%S') print(f'Difference between {t1} and {t2} is {self.diff.seconds} seconds') def main(): ''' Take two dates and find the difference between them ''' # use datetime.strptime() function to create time object # pass string in this format %H:%M:%S # H is Hour, M is Minute and S is Second time_format = '%H:%M:%S' time1 = datetime.strptime('12:45:01', time_format) time2 = datetime.strptime('11:30:00', time_format) time_diff = TimeDifference(time1, time2) time_diff.get_difference() if __name__ == '__main__':
main()