How to Create a Simple Alarm Clock in Python

If you’re a Python beginner, this simple alarm clock is an excellent hands-on introduction.


There are many exercises you can do to strengthen your Python skills. One such exercise is an alarm clock that you can write as a single script file. You can also run it from a command prompt.


In the alarm clock script, the user has to set the time at which the alarm clock should ring. The Python script then displays a “wake up” message to the user when the alarm goes off.

You can also add a countdown to show the user how long to wait before the alarm goes off.


How to set the alarm

Create a Python script and add the initial printed instructions to ask the user when to set the alarm. If you are unfamiliar with some parts of Python syntax, you can look at some basic Python examples to get the basics.

  1. Create a new file and go to it alarm.py.
  2. Open the Python script with any text editor like Notepad++.
  3. Import both the datetime and time modules at the top of the file. The program uses these to calculate how long to wait before the alarm goes off. You can use Python’s timing engine to delay execution, among other things.
    import datetime
    import time
  4. Add a while loop. Inside the while loop, ask the user to enter a valid alarm time in the format [hour:minute]. The while loop repeats if the user enters an invalid number.
    invalid = True

    while(invalid):
    print("Set a valid time for the alarm (Ex. 06:30)")
    userInput = input(">> ")

  5. Inside the while loop, convert the user’s input into an array that separates the hour value from the minute value.
        
    alarmTime = [int(n) for n in userInput.split(":")]
  6. While still inside the while loop, validate both the hourly and minute values. The hour should be a number between 0 and 23, and the minute should be a number between 0 and 59. If these conditions are not met, the invalid boolean value will cause the while loop to repeat and prompt the user to enter a new value.
        
    if alarmTime[0] >= 24 or alarmTime[0] < 0:
    invalid = True
    elif alarmTime[1] >= 60 or alarmTime[1] < 0:
    invalid = True
    else:
    invalid = False

How to count how long you have to wait until the alarm clock rings

Wait for the alarm to sound by counting how many seconds the program has to wait.

  1. Under the while loop, convert the wake up time to the second it is during the day. For reference: There are 86400 seconds in a day. If the user enters 00:01 (one minute past midnight), the alarm time in seconds is 60. If the user enters 23:59, the alarm time in seconds is 86340.

    seconds_hms = [3600, 60, 1]
    alarmSeconds = sum([a*b for a,b in zip(seconds_hms[:len(alarmTime)], alarmTime)])
  2. Use the datetime.now() function to get the current time. Convert the current time to seconds.
    now = datetime.datetime.now()
    currentTimeInSeconds = sum([a*b for a,b in zip(seconds_hms, [now.hour, now.minute, now.second])])
  3. Calculate the number of seconds until the alarm clock rings.
    secondsUntilAlarm = alarmSeconds - currentTimeInSeconds
  4. If the time difference is negative, it means that the alarm needs to be set for the next day.
    if secondsUntilAlarm < 0:
    secondsUntilAlarm += 86400
  5. Display a message to the user to let them know the alarm was successfully set.
    print("Alarm is set!")
    print("The alarm will ring at %s" % datetime.timedelta(seconds=secondsUntilAlarm))

How to ring the alarm

To sound the alarm, wait the remaining seconds before printing a “Wake up!” message to the user.

  1. Use time.sleep to wait the required number of seconds before the alarm needs to go off.
    time.sleep(secondsUntilAlarm)
  2. Display the “wake up” message to the user when the alarm goes off.
    print("Ring Ring... time to wake up!")

How to add a countdown before the alarm goes off

To add a countdown for each second, use a for loop to print the remaining seconds to the user.

  1. Replace the time.sleep line. Add a for loop for each second until the alarm goes off and show the user the remaining seconds.
    for i in range(0, secondsUntilAlarm):
    time.sleep(1)
    secondsUntilAlarm -= 1
    print(datetime.timedelta(seconds=secondsUntilAlarm))

How to run the alarm clock program

Run the script by navigating to the file from the command line. Use the python command to start the script and set a wake up time.

  1. Open a command prompt or terminal. Browse to the location of your alarm.py file. For example, if you saved your Python file to the desktop, use cd Desktop.
    cd Desktop
  2. Use the python command to run the python script.
    python alarm.py
  3. Set a valid time for the alarm in the format of [hour:minute]. For example 4:30.
  4. The alarm will set itself and start a countdown every second until the alarm is due to go off. Wait for the alarm clock to count down.
  5. Once the program finishes the countdown, the program will display a message telling you that the alarm is going off.

Create simple programs with Python

An alarm clock is a good exercise to practice to sharpen your Python skills. You can write the alarm clock app in a single script file and run it from a command line. At runtime, the program prompts the user to enter a valid time to set the alarm.

When the alarm is set, calculate how many seconds you have to wait before the alarm goes off. Make the program wait long enough before showing a message to the user when the alarm goes off.

You can also recreate this wake-up exercise in other languages. You can learn how to create a digital clock using HTML, CSS and JavaScript.

Leave a Reply

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