Welcome everyone, today we are going to build an Alarm Clock using Python.
How do an Alarm Clock works?
An alarm clock usually requires you to set the specific time you want the alarm to ring. Once you have set your preferred time, the alarm will continuously match the time you provided with the current time. As soon as both the time matches, the alarm rings.
This is a very general idea of how usually an real alarm clock works. The alarm clock we will be building will follow the same mechanism.
Project Setup
Install required modules/libraries
Alright, so first things first!
In this project, we are going to use some external modules which are already made available by other developers. These modules will help us save a lot of time and effort. All we have to do is import them into our project to get started.
Importing modules is pretty simple. All you have to do is run a simple pip install
command from terminal & our specified module will be downloaded in our system.
We need 2 different modules for our project - datetime
& playsound
.
Let's run pip install command and download both of these modules.
pip install datetime
datetime
- We will use this module to obtain current time which is not possible without this module.
pip install playsound
playsound
- We will use this module to play our alarm tone once the alarm rings.
Download alarm ringtone
We are almost there! One last thing before we start our project, we have to download a ringtone which will be played when our alarm goes off.
You can download an alarm tone from here. Not just alarm tones, you can use any kind of music you like for this project. All you have to do is make sure that the file extension of the audio file is .wav
. Another thing to make sure is that try to keep the audio file in the same folder as your code.
Let's Code
So the first we are going to do is, of course, import both of our modules, we just installed.
from datetime import datetime
from playsound import playsound
Both of our modules are now ready to use.
Now let's ask the user for the time when the alarm will go off.
alarm_time = input("Enter time in 'HH:MM:SS AM/PM' format: ")
We need to have a pre-defined format in which the user will enter the time. Here we are using a standard time format HH:MM:SS AM/PM
which asks for Hour, minute, second & period (AM/PM). We will save this input into alarm_time
variable.
Now we know human errors are very possible and hence we need some way to make sure that the time input the user has provided is exactly in the format we asked for.
To do this we will create a function which will do the job of validating the user-provided time, if the time format is unexpected or invalid then our function will display the message on the console and will ask the user to re-enter the time.
def validate_time(alarm_time):
if len(alarm_time) != 11:
return "Invalid time format! Please try again..."
else:
if int(alarm_time[0:2]) > 12:
return "Invalid HOUR format! Please try again..."
elif int(alarm_time[3:5]) > 59:
return "Invalid MINUTE format! Please try again..."
elif int(alarm_time[6:8]) > 59:
return "Invalid SECOND format! Please try again..."
else:
return "ok"
Here is our function called validate_time
. Let's break it down and understand what is going on -
- Our function accepts the user input as a parameter
alarm_time
. -
In first
if
statement, atlen(alarm_time) != 11
we are checking the length of user input to be exactly 11 characters. If not then it willreturn
a statement, asking the user to re-enter the value. If the user input is exactly 11 characters long, thenelse
block will execute, this is where the more in-depth validation of our user input happens. -
In the first if statement within else block, we are validating the first two characters of our input which are
HH
. There could be a slight chance that user may enter invalid hour values like something more than 12 hours. Here atalarm_time[0:2]
, we are using a slicing operator to access the first two characters of user input. The input is not more than 12 hours then the execution will move forward to the next conditional statement. But if the input is more than 12 hours, then it willreturn
a statement asking the user to re-enter the time. - Next two conditional statements do the same job as the first, comparing minutes & seconds respectively.
- If the input is all good then,
else
block of our function will return an OK. Now, this is where the job of our function is over.
Awesome! Our validate_time
function is now ready to use!
Now it's time to call our function.
while True:
alarm_time = input("Enter time in 'HH:MM:SS AM/PM' format: ")
validate = validate_time(alarm_time.lower())
if validate != "ok":
print(validate)
else:
print(f"Setting alarm for {alarm_time}...")
break
Here we are storing the output of the function into a variable validate which we are using to judge whether the input is valid or not. If it is not valid then the user will be prompted to enter the time again. If not then the execution will head to the next step.
Now we are sure that the input provided by the user is valid and now we can separately store the values into different variables. Have a look at the code.
alarm_hour = alarm_time[0:2]
alarm_min = alarm_time[3:5]
alarm_sec = alarm_time[6:8]
alarm_period = alarm_time[9:].upper()
Here we are using slicing operator to store the specific unit of time into specific variables. HH
will be stored in alarm_hour
, MM
in alarm_min
and so on.
Coming up next, we now have to get the current time to compare it with the user-provided time.
now = datetime.now()
current_hour = now.strftime("%I")
current_min = now.strftime("%M")
current_sec = now.strftime("%S")
current_period = now.strftime("%p")
Remember our datetime
module we imported at the beginning of our project. We are finally gonna make use of it.
First, we are using datetime.now()
to obtain the current time and we are storing this data in now
variable.
Next up we are using % notation to extract specific time data from now variable. This is exactly similar to what we just did with user input. now.strftime()
is used to the data in string format for comparison.
Awesome! We are almost done!
if alarm_period == current_period:
if alarm_hour == current_hour:
if alarm_min == current_min:
if alarm_sec == current_sec:
print("Wake Up!")
playsound('D:/Library/Documents/Projects/Coding/Beginner Python Projects/Alarm Clock/alarm.wav')
Now, this is were the main mechanism of our alarm lies. We are simply using if statements to compare current time & user time.
Here, if the user & current period (AM/PM) matches then the next if
statement is executed which will make the comparison between user input hour & current hour. This same process repeats until the last if
statement is executed.
Finally when the last if
statement is executed and if it matches, the Wake Up!
will be printed on console & the alarm tone will be played.
To play alarm tone we are making use of our playsound
module. All we did is passed the absolute address of our audio file to the playsound()
and it played the audio file as per our request.
Now before we wrap up, it is important for us to put all the code we wrote for the final part, into a loop so that it keeps executing until our alarms rings.
while True:
now = datetime.now()
current_hour = now.strftime("%I")
current_min = now.strftime("%M")
current_sec = now.strftime("%S")
current_period = now.strftime("%p")
if alarm_period == current_period:
if alarm_hour == current_hour:
if alarm_min == current_min:
if alarm_sec == current_sec:
print("Wake Up!")
playsound('D:/Library/Documents/Projects/Coding/Beginner Python Projects/Alarm Clock/alarm.wav')
break
Here looks good right... We also added a break
statement at the end so that the execution of our alarm will stop once the alarm has rung.
YOU DID IT! GIVE YOURSELF A PAT ON THE BACK ⭐
Source Code
You can find the complete source code of this project here -
mindninjaX/Python-Projects-for-Beginners
Support
Thank you so much for reading! I hope you found this beginner project useful.
If you like my work please consider Buying me a Coffee so that I can bring more projects, more articles for you.
Also if you have any questions or doubts feel free to contact me on Twitter, LinkedIn & GitHub. Or you can also post a comment/discussion & I will try my best to help you :D
Top comments (4)
Rock enthusiasts, are you ready to inject a dose of sonic adrenaline into each call? If you're looking for powerful melodies, electrifying guitar riffs and rhythms that make you want to move, sonnerieportable.com/ has everything you need to find the rock ringtone of your dreams.
I am thankful for your response to their blog. In the future, You will likely share lots of helpful and interesting values. I hope it will workful all the visitors.
كيفية عمل سحر التفريق بين الزوجين
Thanks for share the code
You're welcome Joel 😇 Hope you liked the tutorial 😃
Some comments have been hidden by the post's author - find out more