如何在 Python 中循环我的倒数计时器?

How to loop my countdown timer in Python?

我正在尝试循环我的计时器,所以它会告诉我还剩多少秒。现在它只显示从启动脚本开始还剩多少秒,但我希望它每秒都在变化。 我要 运行 这个脚本 24/7,所以我需要实时结果。

我的计时器:

from datetime import datetime
from threading import Timer
import time


x = datetime.now()
y=x.replace(hour=12, minute=0, second=0)
t=y-x
secs=t.seconds

我在想while循环,但我不知道如何在这段代码中使用它。如果你愿意,你可以更改我的计时器我只想让它告诉我指定时间还剩多少秒。

我是怎么解决的:

from datetime import datetime
from threading import Timer
import time


while True:
    time.sleep(1)
    x=datetime.today()
    y=x.replace(hour=17, minute=10, second=0)
    t=y-x
    secs=t.seconds

它“说”“你好!” 4:20 的每一天。您需要在线程上调用 time_to_sleep 或 运行 它。此外,您可以更改您的时间 (HOURMINUTESECOND) 和频率 (NEXT_DAY)

from datetime import datetime, timedelta

from time import sleep
HOUR = 4
MINUTE = 20
SECOND = 0
NEXT_DAY = 1

def time_to_sleep():
    a = datetime.now()
    a += timedelta(days=NEXT_DAY)

    a = a.replace(hour=HOUR, minute=MINUTE, second=SECOND)

    return (a - datetime.now()).total_seconds()

# you may wont to run this on a thread 
def your_print():
    while True:
        sleep(time_to_sleep())
        print("Hello!")
import time, datetime

designated_date = datetime.datetime(2021, 1, 6, 15, 8, 24) # designated_date
designated_time = time.mktime(designated_date.timetuple()) # designated unix time in seconds

while True:
    time.sleep(1)         # 1 second delay
    current_time = int(time.time())      # every second get current unix time
    left = designated_time - current_time # calculation how much seconds left to desingated time
    print(left) # print results