如何在Python脚本中不断更新时间变量?

时间:2019-06-20 17:32:16

标签: python datetime if-statement time

下面有一条if语句,我想每天每天上午11:45执行。问题是,当我运行我的Python脚本时,result.tm_minresult.tm_hour是静态的,无论我最初启动该脚本时是什么时间。我需要一些方法来使这些值随时钟实时更改。因此,当时间从11:44变为11:45时,result.tm_min也从44变为45,从而允许执行以下if语句。如果我可以得到任何帮助,那就太好了。

我目前正在使用时间和日期时间库。

if result.tm_hour == 11:
        if result.tm_min == 45:

            post_number = random.randint(1, 5)
            noun_number = random.randint(1, noun_expand_count)
            verb_number = random.randint(1, verb_expand_count)

            noun_file = open("nouns.txt", "r")
            get_noun_line = noun_file.readlines()
            new_noun = get_noun_line[noun_number].strip()
            noun_file.close()

            verb_file = open("verbs.txt", "r")
            get_verb_line = verb_file.readlines()
            new_verb = get_verb_line[verb_number].strip()
            verb_file.close()

            post_file = open("things_to_do.txt", "r")
            get_post_line = post_file.readlines()
            new_post = get_post_line[post_number].strip()
            post_file.close

            message = "@joerogan Hello Joe, today's top two priorities are to:", new_post, new_verb, new_noun
            print(message)
            #api.update_status(message)

编辑:好的,我为schedule模块安装了一个pip,试图重写一些代码,但是我什么都没得到。

def post():
post_number = random.randint(1, 5)
noun_number = random.randint(1, noun_expand_count)
verb_number = random.randint(1, verb_expand_count)

noun_file = open("nouns.txt", "r")
get_noun_line = noun_file.readlines()
new_noun = get_noun_line[noun_number].strip()
noun_file.close()

verb_file = open("verbs.txt", "r")
get_verb_line = verb_file.readlines()
new_verb = get_verb_line[verb_number].strip()
verb_file.close()

post_file = open("things_to_do.txt", "r")
get_post_line = post_file.readlines()
new_post = get_post_line[post_number].strip()
post_file.close

message = "@joerogan Hello Joe, today's top two priorities are to:", new_post, new_verb, new_noun
print(message)
#api.update_status(message)
return

class MyStreamListener(tweepy.StreamListener):
    def on_status(self, status):
        global noun_expand_count, verb_expand_count
        status = status._json['text']

        schedule.every().minute.do(post)

1 个答案:

答案 0 :(得分:1)

在检查前立即重新计算当前时间:

current = datetime.now()
if current.hour == 11 and current.minute == 45:
    # annoy Joe Rogan

但是,正如其他人所评论的那样,最好使用诸如cron之类的专用任务调度系统。