Timer Management

Write a class Timer that can start, stop, and reset a timer. The class should have a method to display the current time in minutes and seconds.

Example 1:

Input: 
timer = Timer()
timer.start_timer()
# waits for some time
timer.stop_timer()
print(timer.get_time())

Output: 
# Output varies depending on the wait time

Python’s built-in time module can be used to get the current time in seconds.

import time

class Timer:
    def __init__(self):
        self.start_time = 0
        self.end_time = 0

    def start_timer(self):
        self.start_time = time.time()

    def stop_timer(self):
        self.end_time = time.time()

    def get_time(self):
        elapsed_time = self.end_time - self.start_time
        minutes = int(elapsed_time // 60)
        seconds = int(elapsed_time % 60)
        return f"{minutes} minutes, {seconds} seconds"

    def reset_timer(self):
        self.start_time = 0
        self.end_time = 0

© Let’s Data Science

LOGIN

Unlock AI & Data Science treasures. Log in!