如何在Python上发出简单的警报

2024-04-27 00:41:40 发布

您现在位置:Python中文网/ 问答频道 /正文

我试着用Python发出一个简单的警报,但是不管我怎么做,似乎都不起作用。我最近做了一个计时器,但闹钟会有用一点。 我对Python还很陌生,所以我不太了解所有的规则和语法。

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.


Tags: theimportfalsedatetimetimeos规则语法
3条回答

使用以下命令循环到下一分钟(或调整秒数等)

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)

若要适应秒数,请删除seconds = rn.second,然后将下一行中的minutes更改为seconds

工作原理

从当前时间中删除秒和微秒,然后添加1分钟,因此将其舍入到下一整分钟。

只需替换: 如果rn=“18:00:00.000000”:

使用: 如果rn>;=“18:00:00.000000”:

这里的技术问题是,如果一次又一次地调用datetime.now(),则无法总是以足够快的速度调用它以获得所有可能的值。所以==应该是>=。然而,这仍然不是很好。

一个更好的方法是使用time.sleep()而不是循环。

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")

相关问题 更多 >