How to schedule simple alarms in Python?

Creating a simple alarm clock is one of the basic projects that can help you understand the basics of time manipulation, running system commands, playing audio files and other such essential topics. In this tutorial, we will be learning how to build one using Python's datetime module and pygame for audio playback.

Installation and Setup

For playing the audio file, we will be using the PyGame module. This module does not come pre-packaged with Python, so we need to install it using pip ?

pip install pygame

Next, we import the necessary modules and initialize the mixer ?

import datetime
from pygame import mixer

# Initialize the mixer
mixer.init()
print("Pygame mixer initialized successfully!")
Pygame mixer initialized successfully!

Building the Basic Alarm Clock

Let's create a simple alarm that demonstrates the core concept. This version uses a fixed alarm time to show how the alarm logic works ?

import datetime
from pygame import mixer
import time

mixer.init()

# Set alarm for demonstration (next minute)
current_time = datetime.datetime.now()
alarm_hour = current_time.hour
alarm_minute = current_time.minute + 1

print(f"Current time: {current_time.strftime('%H:%M')}")
print(f"Alarm set for: {alarm_hour:02d}:{alarm_minute:02d}")

# Check if alarm time matches current time
def check_alarm():
    now = datetime.datetime.now()
    if now.hour == alarm_hour and now.minute == alarm_minute:
        print("ALARM! Time to wake up!")
        return True
    return False

# Simulate checking (normally you'd use a loop)
print("Checking alarm...")
result = check_alarm()
print(f"Alarm triggered: {result}")
Current time: 14:23
Alarm set for: 14:24
Checking alarm...
Alarm triggered: False

Complete Interactive Alarm Program

Here's the complete program that takes user input and continuously monitors for the alarm time. Note that this requires pygame and an audio file to work properly ?

import datetime
from pygame import mixer
import time

# Initialize pygame mixer
mixer.init()

def get_alarm_time():
    """Get alarm time from user input"""
    hour = int(input("At what hour do you want the alarm? (1-12): "))
    minute = int(input("Specify exact minutes (0-59): "))
    am_pm = input("AM or PM? ").lower().strip()
    
    # Convert to 24-hour format
    alarm_hour = hour
    if am_pm == "pm" and hour != 12:
        alarm_hour = hour + 12
    elif am_pm == "am" and hour == 12:
        alarm_hour = 0
        
    return alarm_hour, minute

def play_alarm():
    """Play alarm sound"""
    try:
        # You need to have an audio file named 'alarm.mp3' in your directory
        mixer.music.load("alarm.mp3")
        mixer.music.play()
        print("? ALARM! Time to wake up! ?")
    except:
        print("? BEEP! BEEP! ALARM! ?")  # Fallback if no audio file

def run_alarm():
    """Main alarm function"""
    alarm_hour, alarm_minute = get_alarm_time()
    
    print(f"Alarm set for {alarm_hour:02d}:{alarm_minute:02d}")
    print("Waiting for alarm time... (Press Ctrl+C to stop)")
    
    try:
        while True:
            current_time = datetime.datetime.now()
            
            if (current_time.hour == alarm_hour and 
                current_time.minute == alarm_minute):
                play_alarm()
                break
            
            # Sleep for a short time to avoid constant checking
            time.sleep(30)  # Check every 30 seconds
            
    except KeyboardInterrupt:
        print("\nAlarm cancelled!")

# Uncomment the line below to run the interactive alarm
# run_alarm()

Key Components Explained

Time Conversion

The program converts 12-hour format to 24-hour format for easier comparison ?

def convert_to_24_hour(hour, am_pm):
    if am_pm == "pm" and hour != 12:
        return hour + 12
    elif am_pm == "am" and hour == 12:
        return 0
    else:
        return hour

# Example conversions
examples = [
    (1, "am"), (12, "am"), (1, "pm"), (12, "pm")
]

for hour, period in examples:
    converted = convert_to_24_hour(hour, period)
    print(f"{hour} {period.upper()} = {converted:02d}:00 (24-hour)")
1 AM = 01:00 (24-hour)
12 AM = 00:00 (24-hour)
1 PM = 13:00 (24-hour)
12 PM = 12:00 (24-hour)

Efficient Time Checking

Instead of checking every millisecond, we check every 30 seconds to reduce CPU usage while maintaining reasonable accuracy ?

import time
import datetime

def demonstrate_checking():
    print("Demonstrating efficient time checking...")
    start_time = datetime.datetime.now()
    
    for i in range(3):
        current = datetime.datetime.now()
        elapsed = (current - start_time).seconds
        print(f"Check {i+1}: {current.strftime('%H:%M:%S')} (elapsed: {elapsed}s)")
        time.sleep(2)  # Simulate 30-second intervals with 2 seconds for demo

demonstrate_checking()
Demonstrating efficient time checking...
Check 1: 14:23:45 (elapsed: 0s)
Check 2: 14:23:47 (elapsed: 2s)
Check 3: 14:23:49 (elapsed: 4s)

Enhanced Features

You can extend this basic alarm with additional features like multiple alarms, snooze functionality, or different alarm tones. For production use, consider using task schedulers like cron on Linux or Task Scheduler on Windows instead of continuous loops.

Conclusion

This tutorial demonstrates how to create a simple alarm clock in Python using datetime for time handling and pygame for audio playback. The key concepts include time format conversion, efficient polling, and audio file management for creating functional scheduling applications.

---
Updated on: 2026-03-27T11:11:41+05:30

547 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements