How to Build an Alarm Clock in Python: Python Project for beginners - Post 44
- Anubhav Somani
- Sep 8
- 2 min read

Let's build a Simple Alarm Clock. This is a great beginner project because it introduces how to work with time, run a persistent background task, and interact with the system to play sound.
First, here is the explanation of how the project is built.
How the "Simple Alarm Clock" is Made
The Core Idea: The goal is to create a command-line program that functions as a simple alarm clock. The user will set a specific time, and when the current time matches the set time, the program will play an alarm sound.
Required Modules: This project uses the built-in datetime and time modules. It also requires an external library, playsound, to play the alarm sound. You'll need to install it first using pip in your terminal: pip install playsound==1.2.2 (Note: Specifying version 1.2.2 can help avoid common issues with this library). You will also need to have a sound file (like alarm.mp3 or alarm.wav) saved in the same directory as your Python script.
Getting User Input: The program needs to know when to set the alarm. We'll ask the user to input the alarm time in a clear, 24-hour format: HH:MM:SS (e.g., 14:30:00 for 2:30 PM). We'll add a simple check to make sure the format seems correct.
The Main Loop: The core of the program is a while True loop that continuously checks the time.
Get Current Time: Inside the loop, we get the current time using datetime.datetime.now() and format it into the same HH:MM:SS string format we asked the user for.
Check for Match: We use a simple if statement to compare the current_time string with the alarm_time string set by the user.
Pause: To prevent the program from using all the computer's processing power by checking the time millions of times a second, we add time.sleep(1). This makes the loop pause for one second before checking again, which is perfect for a clock.
Triggering the Alarm:
When the if condition is met (the times match), we'll print a "Wake up!" message.
Then, we'll call the playsound() function, passing it the name of our sound file (e.g., playsound('alarm.mp3')).
After the alarm has sounded, we use break to exit the while loop and end the program.
Adding a Visual Cue: While the loop is running, it's helpful to print the current time to the screen so the user can see it ticking. To make it look like the time is updating on a single line, we can use a carriage return (\r) in our print statement.



Comments