Categories We Write About

Create a simple time tracker in Python

Here’s a simple time tracker in Python that lets you start, stop, and view the elapsed time for a task. It’s a command-line script with basic functionality:

python
import time class TimeTracker: def __init__(self): self.start_time = None self.elapsed = 0 def start(self): if self.start_time is not None: print("Timer is already running.") else: self.start_time = time.time() print("Timer started.") def stop(self): if self.start_time is None: print("Timer is not running.") else: end_time = time.time() self.elapsed += end_time - self.start_time self.start_time = None print(f"Timer stopped. Total time: {self.format_time(self.elapsed)}") def reset(self): self.start_time = None self.elapsed = 0 print("Timer reset.") def status(self): if self.start_time is not None: current = time.time() - self.start_time + self.elapsed else: current = self.elapsed print(f"Current elapsed time: {self.format_time(current)}") def format_time(self, seconds): minutes, seconds = divmod(int(seconds), 60) hours, minutes = divmod(minutes, 60) return f"{hours:02}:{minutes:02}:{seconds:02}" def main(): tracker = TimeTracker() print("Simple Time Tracker") print("Commands: start, stop, reset, status, exit") while True: command = input("Enter command: ").strip().lower() if command == "start": tracker.start() elif command == "stop": tracker.stop() elif command == "reset": tracker.reset() elif command == "status": tracker.status() elif command == "exit": if tracker.start_time is not None: tracker.stop() print("Exiting Time Tracker.") break else: print("Invalid command.") if __name__ == "__main__": main()

Features:

  • start begins tracking time.

  • stop halts tracking and adds to total elapsed.

  • reset clears all tracking.

  • status shows current tracked time.

  • exit stops tracking and exits the app.

You can run this script in any terminal or command prompt that supports Python.

Share This Page:

Enter your email below to join The Palos Publishing Company Email List

We respect your email privacy

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

Categories We Write About