visit
Welcome everyone, today we are going to build an Alarm Clock using Python.
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.
You can download an alarm tone from . 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.
from datetime import datetime
from playsound import playsound
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, at len(alarm_time) != 11 we are checking the length of user input to be exactly 11 characters. If not then it will return a statement, asking the user to re-enter the value. If the user input is exactly 11 characters long, then else 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 at alarm_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 will return 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
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')
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
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 ⭐
You can find the complete source code of this project here -
Also published on: //dev.to/mindninjax/alarm-clock-python-project-4jn4