Python-暂停1分钟后再次运行代码
如果一周中的某一天是星期一,而某个小时是下午4点,那么我会专门运行代码。我创建了一个从“周一”开始的工作日数组,它通过了第一次检查,但是我正在测试,看看当时间不是下午4点时,它是否应该再暂停一分钟,然后继续循环。然而,它只是在暂停时暂停,直到并没有继续 我的假设是,即使我正在传递pause.until(datetime())day/time变量,它仍然会在时钟到达下一分钟时继续 感谢您的帮助Python-暂停1分钟后再次运行代码,python,discord,bots,Python,Discord,Bots,如果一周中的某一天是星期一,而某个小时是下午4点,那么我会专门运行代码。我创建了一个从“周一”开始的工作日数组,它通过了第一次检查,但是我正在测试,看看当时间不是下午4点时,它是否应该再暂停一分钟,然后继续循环。然而,它只是在暂停时暂停,直到并没有继续 我的假设是,即使我正在传递pause.until(datetime())day/time变量,它仍然会在时钟到达下一分钟时继续 感谢您的帮助 import discord import os from keepalive import keep_
import discord
import os
from keepalive import keep_alive
import calendar
from datetime import date
from datetime import datetime
import time
import pytz
import pause
while True:
#get todays date into an array and convert to value variables
today = date.today().isoformat()
year = today[0:4]
month = today[5:7]
day = today[8:10]
#need to format the string into hour minute second
hour = datetime_London.strftime("%H")
minute = datetime_London.strftime("%M")
second = datetime_London.strftime("%S")
#get the current time from pytz module
tz_London = pytz.timezone('Europe/London')
datetime_London = datetime.now(tz_London)
#convert strings to int's for calendar.weekday function
year = int(year)
month = int(month)
day = int(day)
hour = int(datetime_London.strftime("%H"))
minute = int(datetime_London.strftime("%M"))
second = int(datetime_London.strftime("%S"))
#turn current date into the weekday
weekday = calendar.weekday(year, month, day)
if weekday != 0:
pause.until(datetime(year,month,day + 1))
elif weekday == 0:
if hour != 16:
print("datetime before pause: ", datetime(year,month,day,hour, minute, second))
pause.until(datetime(year,month,day,hour,minute + 1, second))
print("datetime after pause: ", datetime(year,month,day,hour, minute, second))
怎么样
导入时间
睡眠时间(指定秒数)
@ProblemsLoop的建议成功了-我已将pause.until更改为pause.minutes(1),并在一分钟后再次开始运行代码
if weekday != 0:
pause.days(1)
elif weekday == 0:
if hour != 16:
print("datetime before pause: ", datetime(year,month,day,hour, minute, second))
pause.minutes(1)
print("datetime after pause: ", datetime(year,month,day,hour, minute, second))
将pause.until(…)
更改为pause.minutes(1)
可以使代码更干净、更安全。至于为什么不能使用新的datetime对象,可能是因为您没有传递tzinfo。如果您确实需要创建一个新的datetime对象,您只需要传递它
pause.until(datetime(year, month, day, hour, minute + 1, second, tzinfo=tz_London))
一些补充说明:
- 你的许多陈述似乎是多余的。对象具有属性,
等。因此,您不需要仅获取对象的特定部分year、month、day
datetime\u London
print("datetime before pause: ", datetime_London)
print("datetime before pause: ", datetime.now(tz_London))
你的剧本在做什么?如果在windows上,最好创建某种cron作业或使用windows调度?我实际上是在尝试创建一个Discord bot,它将在每周一下午4点向Discord客户端/服务器/频道发送消息。我是Python新手,正在慢慢地适应它。我可能不得不看一看cron,正如我之前提到的,但一开始我并不太理解它。我认为可能所有脚本都可以这样做。在描述中,您提到它应该再暂停一分钟,但在代码中,您应该再暂停一天,而不是几分钟。hi@theonepatriot,欢迎使用!你能发布一个完整的最小工作示例,包括导入吗?特别是,我想知道pause.till()是从哪里来的。@balu谢谢你的欢迎!我已经更新了问题以显示导入。这个导入简单地称为暂停:)啊,很高兴知道!谢谢-我会修改多余的代码。
print("datetime before pause: ", datetime_London)
print("datetime before pause: ", datetime.now(tz_London))