我如何对 Python 说在给定时间执行指令?

How can I say to Python to do an instruction at a given time?

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

例如:

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

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

但是我不想使用函数!

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

Windows and Linux都支持cron操作

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

您可以轻松地使用 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

确保我缩进正确,因为一个 space 可以勾选 python :)。

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

需要的模块: datetime time.sleep

现在我们准备好了。 timing = [10,0,0] 设置您要使用的时间(稍后您会明白为什么)

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

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

data == timing 确保时间与您要求的时间一致。

Note that the timing is in UTC Go to Getting the correct timezone offset in Python using local timezone to know how to find your offset.

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