2017-03-26 92 views
3

私は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.

+0

'datetime.now()'が* exactly * '" 18:00:00.000000 "'の場合にのみ、アラームが発生します。 17:59:59.999999で 'datetime.now()'を呼び出し、18:00:00.000001で呼び出すとどうなりますか? –

+0

18:00:00.000000を正確に叩くことは非常に幸運なことです。 – timgeb

+0

「<' or '>」の範囲を使用する必要がありますか? –

答えて

1

ちょうど置き換える: RN ==場合は、 "18:00:00.000000":

付: ":00:00.000000 18": は> =をrnを場合

1

秒間に適応するために

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分後に加算し、次の分に丸めます。

+0

秒に適応したバージョンを使用すると、実際にはアラームの方が効果的です。 –

2

ここでの技術的な問題があればということです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") 
関連する問題