【问题标题】:Make program sleep for X seconds in python [closed]在python中使程序休眠X秒[关闭]
【发布时间】:2014-05-28 13:23:43
【问题描述】:

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

伪代码: X = 上午 6:00 - 当前时间 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:

【问题讨论】:

标签: python datetime time pygame timedelta


【解决方案1】:

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

【讨论】:

  • 你会建议什么?
  • 将 sleep() 调用包装在一个循环中并手动跟踪时间。 samtregar 在上述问题中的回答有一个示例 trusty_sleep() 函数。
【解决方案2】:

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

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

【讨论】:

  • 我的问题问错了,我需要找出 CurrentTime 和 6:00AM 之间的区别,有什么想法吗?
  • 当我评估 target_dt = datetime.combine(d, time(6,0)) 在 python 命令行中它抛出错误 Python 3.4.0 >>> target_dt = datetime.combine(d, time (6,0)) Traceback(最近一次调用):文件“”,第 1 行,在 NameError: name 'datetime' is not defined >>>
  • @user3532319 你运行导入线了吗? from datetime import datetime, date, time, timedelta
猜你喜欢
  • 2010-09-27
  • 2012-07-19
  • 2021-06-21
  • 2013-06-11
  • 2021-12-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-06-08
相关资源
最近更新 更多