【问题标题】:Running Python at a Certain Time with Datetime使用 Datetime 在特定时间运行 Python
【发布时间】:2015-01-06 05:45:53
【问题描述】:

我想在每天早上 8 点执行脚本的一部分。我创建了一个没有语法错误但无法正常工作的简化测试用例。我认为这可能是因为我的 if 语句将时间用作字符串,但它不会以任何其他方式编译。我做错了什么?

import datetime

while True:
    if datetime.datetime.now().time()  == "19:00:00.000000":
        print "it's time!"

【问题讨论】:

  • 你为什么不直接使用 cron?
  • 不熟悉 cron,但这应该仍然有效
  • 鉴于您是特定于毫秒的,它可能不是,因为毫秒是非常短的时间,很容易错过它。只要坚持 cron,google 就能带你走上正确的道路。

标签: python time


【解决方案1】:

如果您在一个带有cron 的系统上,那么最好设置一个 cron 作业。但是,您的问题可以在 Python 中解决:

首先,正如您所说,datetime.datetime.now().time() 返回一个 datetime.time 对象,而不是字符串:

In [89]: datetime.datetime.now().time()
Out[89]: datetime.time(19, 36, 13, 388625)

此外,虽然 datetime.datetime.now().time() == datetime.time(19, 0) 会是 有效的Python,你碰巧在右边执行time()的机会 因为datetime.datetime.now() 有微秒,所以时刻非常渺茫 解决。所以最好测试一下当前时间是否在某个范围内 范围。

但是,由于您只想每天运行一次该函数,因此您可以改为测量从现在到您想要运行该函数并休眠该秒数之间的总秒数:

import datetime as DT
import time

while True:
    now = DT.datetime.now()
    target = DT.datetime.combine(DT.date.today(), DT.time(hour=8))
    if target < now:
        target += DT.timedelta(days=1)

    time.sleep((target-now).total_seconds())
    # do something

【讨论】:

  • +1 用于更新答案,并带有关于毫秒精度的大警告。
  • 所以我只想每天运行一次代码,所以如果我在一个范围内测试,如何确保它只发生一次?
  • 在这种情况下,我会安排睡觉,直到该运行该功能。我已经更新了代码以说明我的意思。
  • 这很好用,谢谢。这会占用大量计算机cpu吗?
  • 不,大多数时候it will be sleeping(或运行所需的功能)。
猜你喜欢
  • 1970-01-01
  • 2019-12-26
  • 1970-01-01
  • 1970-01-01
  • 2011-10-07
  • 1970-01-01
  • 2019-08-12
  • 1970-01-01
  • 2021-12-09
相关资源
最近更新 更多