How to make simple alarms on Python
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")
Just replace: if rn == "18:00:00.000000":
With: if rn >= "18:00:00.000000":
Use the following to round to the next minute (or adapt for seconds etc)
import datetime as dt
rn = dt.datetime.now()
# round to the next full minute
rn -= dt.timedelta( seconds = rn.second, microseconds = rn.microsecond)
rn += dt.timedelta(minutes=1)
To adapt for seconds remove seconds = rn.second
and then change minutes
in the next line to seconds
How it works
Removes the seconds and microseconds from the current time and then adds on 1 minute therefore rounding it to the next whole minute.