I'm trying to make a simple alarm using Python but whatever I try it doesn't seem to work. I've just recently made a timer but an alarm would be a little more useful. I'm also pretty new to Python so I'm not really aware of all the rules and syntax.
import datetime
import os
stop = False
while stop == False:
rn = str(datetime.datetime.now().time())
print(rn)
if rn == "18:00:00.000000":
stop = True
os.system("start BTS_House_Of_Cards.mp3")
When I run the file, it prints the time but goes completely past the time I want the alarm to go off at.
Windows 10 has a built-in alarm clock app, which you can set up using the following steps. 1. Type "alarm" into the Windows search box. 2.
The technical problem here is that if you call datetime.now()
over and over again, you can't always call it fast enough to get all of the possible values. So ==
should instead be >=
. However, this still isn't very good.
A much better way to do this is to use time.sleep()
instead of looping.
import datetime
import os
import time
now = datetime.datetime.now()
# Choose 6PM today as the time the alarm fires.
# This won't work well if it's after 6PM, though.
alarm_time = datetime.datetime.combine(now.date(), datetime.time(18, 0, 0))
# Think of time.sleep() as having the operating system set an alarm for you,
# and waking you up when the alarm fires.
time.sleep((alarm_time - now).total_seconds())
os.system("start BTS_House_Of_Cards.mp3")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With