簡體   English   中英

如何在Python腳本中不斷更新時間變量?

[英]How to constantly update time variables in a Python Script?

我下面有一條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)

在檢查之前立即重新計算當前時間:

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

但是,正如其他人所評論的那樣,使用像cron這樣的專用任務調度系統可能會更好。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM