使用日期时间在特定时间运行 Python [英] Running Python at a Certain Time with Datetime

查看:40
本文介绍了使用日期时间在特定时间运行 Python的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I would like to execute a portion of a script at 8 am each day. I have created a simplified test case that has no syntax error, but does not work properly. I think it may be because my if statement is using the time as a string, but it won't compile any other way. What am I doing wrong?

import datetime

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

推荐答案

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

If you are on a system with cron, then it would be better to set up a cron job. However, your problem is fixable from within Python:

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

First, as you noted, datetime.datetime.now().time() returns a datetime.time object, not a string:

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() 有微秒,所以时刻非常渺茫解析度.因此最好测试当前时间是否在某个范围内范围.

Also, although datetime.datetime.now().time() == datetime.time(19, 0) would be valid Python, the chance that you happen to execute time() at just the right moment is very slim since datetime.datetime.now() has microsecond resolution. So it would be better to test if the current time falls within some range.

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

However, since you only want to run the function once per day, you could instead measure the total number of seconds between now and when you want to run the function and sleep that number of seconds:

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

这篇关于使用日期时间在特定时间运行 Python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆