使用日期时间在特定时间运行 Python

编程入门 行业动态 更新时间:2024-10-25 13:23:40
本文介绍了使用日期时间在特定时间运行 Python的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时送ChatGPT账号..

我想在每天早上 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.datetimebine(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屋!

更多推荐

[db:关键词]

本文发布于:2023-04-30 13:07:07,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1395143.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:时间   日期   在特定   Python

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!