How to create a Countdown Timer in Python

If you need to count down a specific amount of time, say for example, when a token is set to expire, then a countdown timer will be useful.

Step 1 – Writing the Python code

Place the following Python code in a file called countdowntimer.py

Option 1 – Text output

import time def countdown(t): while t: mins, secs = divmod(t, 60) timer = '{:02d}:{:02d}'.format(mins, secs) print(timer, end="\r") time.sleep(1) t -= 1 print('Countdown time has elapsed!!') t = input("Enter the time in seconds: ") countdown(int(t))
Code language: Python (python)

Option 2 – Text and speech output

Here we also invoke say which speaks out the text. This is only native to some operating systems.

Note: If you use MacOS, this will work out the box for you!

import time import os def countdown(t): while t: mins, secs = divmod(t, 60) timer = '{:02d}:{:02d}'.format(mins, secs) print(timer, end="\r") time.sleep(1) t -= 1 txt = 'Countdown time has elapsed!!' print(txt) os.system('say "'+txt+'"') t = input("Enter the time in seconds: ") countdown(int(t))
Code language: Python (python)

Step 2 – Calling the Python code

python3 <path_to_file>/countdowntimer.py
Code language: Bash (bash)

Optional Step 3 – Create an Alias

If you use bash then do this:

echo "alias count='python3 <path_to_file>/countdowntimer.py'" >> ~/.bash_profile
Code language: Bash (bash)

If you use zsh then do this:

echo "alias count='python3 <path_to_file>/countdowntimer.py'" >> ~/.zshrc
Code language: Bash (bash)

Now once you’ve reloaded the terminal session by doing one of the following:

  1. source ~/.bash_profile
  2. source ~/.zshrc
  3. Close and reopen your terminal

You can just call count and the application will start.

What input does it expect?

When you first run the application, you can specify the amount of seconds to count down from.

If you enter 30, then it will count down for 30 seconds.

If you enter 3600 (60seconds x 60minutes), then it will count down for an hour.

etc.

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments