Python Program to Create Alarm Clock
datetime to check the current time in a loop and playsound to play an alarm sound when the set time matches, for example: while True: if datetime.now().strftime('%H:%M') == alarm_time: playsound('alarm.mp3').Examples
How to Think About It
Algorithm
Code
from datetime import datetime from playsound import playsound alarm_time = input('Set the alarm time (HH:MM): ') print(f'Alarm set for {alarm_time}') while True: now = datetime.now().strftime('%H:%M') if now == alarm_time: print('Wake up! Alarm ringing...') playsound('alarm.mp3') break
Dry Run
Let's trace setting alarm_time to '07:30' and current time reaching '07:30'.
Input alarm time
User inputs '07:30', so alarm_time = '07:30'
Start loop and get current time
Current time is checked repeatedly, e.g., '07:29', '07:30'
Compare times
When now == alarm_time ('07:30' == '07:30'), condition is True
Trigger alarm
Print message and play sound, then break loop
| Iteration | Current Time | Alarm Time | Match? |
|---|---|---|---|
| 1 | 07:29 | 07:30 | No |
| 2 | 07:30 | 07:30 | Yes |
Why This Works
Step 1: Getting alarm time
We ask the user to enter the alarm time as a string in HH:MM format to know when to trigger the alarm.
Step 2: Checking current time
We use datetime.now().strftime('%H:%M') to get the current time in the same format for easy comparison.
Step 3: Playing alarm
When the current time matches the alarm time, we use playsound to play an alarm sound and notify the user.
Alternative Approaches
from datetime import datetime from playsound import playsound import time alarm_time = input('Set the alarm time (HH:MM): ') print(f'Alarm set for {alarm_time}') while True: now = datetime.now().strftime('%H:%M') if now == alarm_time: print('Wake up! Alarm ringing...') playsound('alarm.mp3') break time.sleep(20)
import threading from datetime import datetime from playsound import playsound def alarm(alarm_time): while True: now = datetime.now().strftime('%H:%M') if now == alarm_time: print('Wake up! Alarm ringing...') playsound('alarm.mp3') break alarm_time = input('Set the alarm time (HH:MM): ') thread = threading.Thread(target=alarm, args=(alarm_time,)) thread.start() print('Alarm is running in background')
Complexity: O(T) time, O(1) space
Time Complexity
The program runs a loop checking the time every iteration until the alarm time is reached, so time depends on how long until the alarm.
Space Complexity
Uses constant space for storing strings and no extra data structures.
Which Approach is Fastest?
Adding time.sleep() reduces CPU load without affecting alarm accuracy much, while threading allows multitasking but adds complexity.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Simple loop | O(T) | O(1) | Basic alarm functionality |
| Loop with sleep | O(T) | O(1) | CPU efficient waiting |
| Threading | O(T) | O(1) | Running alarm alongside other tasks |
time.sleep() inside the loop to avoid high CPU usage while waiting for the alarm time.