How to implement alarm clock in python?
Alarm plays an important role in everyday life. If your python program sets your alarm from your input. Here, is the code follows….
How to do it?
This program starts from importing the built-in files. One is
datetime and another one is time.
- Next one is winsound to create alarm sound.
- First step is to create the set_alarm code.
- Let us get the input from user for hour and minute to set the alarm.
- It is named as alarm_hour,alarm_minute.
- Get the time now.
- Set the alarm time.
- If the time crosses, make it for tomorrow.
- Otherwise, set the sound for the alarm time.
Code:
#import built-in files
import datetime
import time
import winsound
def set_alarm():
# Ask user for
alarm time
alarm_hour =
int(input("Enter hour (0-23): "))
alarm_minute =
int(input("Enter minute (0-59): "))
now =
datetime.datetime.now()
alarm_time =
now.replace(hour=alarm_hour, minute=alarm_minute, second=0, microsecond=0)
# If the time has
already passed today, set it for tomorrow
if alarm_time <
now:
alarm_time +=
datetime.timedelta(days=1)
print(f"Alarm
set for {alarm_time.strftime('%H:%M:%S')}")
# Wait until alarm
time
while True:
current_time =
datetime.datetime.now()
if
current_time >= alarm_time:
print("Wake up! Alarm ringing...")
for _ in
range(5):
winsound.Beep(1000, 500) #
frequency=1000Hz, duration=500ms
time.sleep(0.5)
break
time.sleep(1)
# Run the alarm
set_alarm()
Output:
Run the program in the command line as follows.
C:\raji\blog>python alarm_clock.py
Enter hour (0-23): 21
Enter minute (0-59): 54
Alarm set for 21:54:00
Yes. The python program to implement the alarm clock was
done successfully. Hope, you understood the concept. Keep Coding!!!!!
Comments
Post a Comment