【问题标题】:How can I say to Python to do an instruction at a given time?如何让 Python 在给定时间执行指令?
【发布时间】:2021-12-18 15:53:38
【问题描述】:

我想要一天中的特定时间(例如 10:00:00),我的 if 条件之一激活。

例如:

如果时间是 10:00:00: 打印(“你好世界”)

Imortant:我已经读过这个:Python script to do something at the same time every day

但我不想使用函数!

【问题讨论】:

  • 为什么不想使用函数呢?你可以有一个while True循环,检查它是否是你想要的时间,如果不是,睡眠
  • 解决方案是让您的脚本由 crontab 运行。
  • @Mahrkeenerh 因为我有多个条件:如果 x = 3 和时间 = 10:10:10:做这个指定的工作,我怎么能用一个函数来做这个
  • 你可以这样做if datetime.now().strftime("%H:%M:%S") == '10:00:00':programiz.com/python-programming/datetime/current-time
  • 如果时间合适,你可以做这项工作,并在工作内部检查 x 是否为 3

标签: python time timezone


【解决方案1】:

如果您不使用某个功能但需要在某些时候运行一个简单的脚本,您可以为此使用crons/job schedulers。

WindowsLinux 都支持 cron 操作。

如果您想以编程方式执行此操作,而不是依赖操作系统工具,则需要为其编写服务或长时间运行的进程。

【讨论】:

  • 好的,谢谢您的建议
【解决方案2】:

您可以轻松地使用 datetime 来帮助您。

import datetime
from time import sleep

timing = [10, 0, 0] # Hour, minute, second, in 24 hour time

while True: # Repeat forever
    now = datetime.datetime.now()
    data = [now.hour, now.minute, now.second]
    if data == timing:
        # Code to be executed
        print("Hello World")
        #######
        sleep(1) # To ensure the command is not repeated again
        # break # Uncomment this if you want to execute the command only once

确保我正确缩进,因为一个空格可以勾掉 python :)。

它的工作方式: import datetimefrom time import sleep 导入您需要的必要模块和功能。

需要的模块: datetime time.sleep

现在我们准备好了。 timing = [10,0,0] 设置您想要使用的时间(稍后您会看到原因)

while True 重复循环……不断循环。

now = datetime.datetime.now() 为这么长的一段文字创建了一个快捷方式。

data == timing 确保时间与您要求的时间相符。

注意时间是UTC 转到Getting the correct timezone offset in Python using local timezone 了解如何找到您的偏移量。

UTC-0200(或 -7200 秒)的偏移量意味着您需要增加 2 小时才能获得 UTC。或者,如果您的时区是 UTC+0200,则从您的时间减去 2 小时。

【讨论】:

  • 你需要将sleep放在循环中,否则会跑得太快
  • 非常感谢 Lucas,它运行良好
猜你喜欢
  • 2011-02-22
  • 2011-04-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-06-03
  • 1970-01-01
  • 1970-01-01
  • 2016-06-02
相关资源
最近更新 更多