让程序在python中休眠X秒

时间:2014-04-14 14:19:19

标签: python datetime time pygame timedelta

我正在制作闹钟程序,必须在早上6点之前睡觉(不要发出噪音)。我遇到的问题是我无法让程序等待X秒

伪代码:      X = 6:00 AM - CurrentTime      time.sleep(X)

到目前为止,这是我的代码:

#Imports
import datetime
import time
import pygame

WORDS = ["Wake", "Me", "Tommorow"]

#Make J.A.R.V.I.S. Listen
mic.activeListen():

#Determine time and difference of time
x = datetime.datetime.now()
x = x.total_seconds
print(x)
x = datetime.timedelta()
x = float(x) #time.sleep() Requires a float value.
time.sleep(x) #Sleeps until 6:00 AM
pygame.mixer.init()
pygame.mixer.music.load("alarm.mp3")
pygame.mixer.music.play()
while pygame.mixer.music.get_busy() == True:

2 个答案:

答案 0 :(得分:2)

为了创建代表上午6:00的datetime对象,您需要指定日期。例如。如果你想今天早上6点 (假设它将来发生):

from datetime import datetime, date, time, timedelta
import time
d = date.today()
target_dt = datetime.combine(d, time(6,0))
td = target_dt - datetime.now()
time.sleep(td.total_seconds())

如果你想明天早上6点,请执行:

d = date.today() + timedelta(days=1)
# the rest is the same...

答案 1 :(得分:1)

您不应该信任time.sleep()在预期时间停止等待,因为任何捕获的信号都会终止它(请参阅Upper limit in Python time.sleep()?的答案)。