自动更新的打印时间

Print time that updates automatically

我想在屏幕上打印当前时间(以小时和分钟为单位)并自动更新而不换行,以及打印另一行秒数并在第二行自动更新。提前致谢!这是我目前所拥有的:

import time
from datetime import datetime

while True:
    now = datetime.now()
    current_time = now.strftime("%I:%M %p")
    current_second = now.strftime("%S")
    print("\r" + "Clock: ", current_time, end= ' ')
    print("\r" + "\n" + "Seconds: ", current_second, end=' ')
    time.sleep(1)

这是输出的样子:Output

秒数正常,但时间不对

尝试使用清除方法清除控制台。像这样定义它:

from os import system, name

if name == "nt":
    clear = lambda: system("cls")
else:
    clear = lambda: system("clear")

然后每次循环都调用它

的答案与您的代码相结合,您可以执行以下操作:

import subprocess
import sys
import time
from datetime import datetime

clear = "cls" if sys.platform == "win32" else "clear"
while True:
    now = datetime.now()
    current_time = now.strftime("%I:%M %p")
    current_second = now.strftime("%S")
    print(f"\rClock: {current_time}", flush=True, end="\n")
    print(f"Seconds: {current_second}", flush=True, end="")
    time.sleep(1)
    subprocess.run(clear, shell=True)

这个问题的核心是如何清除控制台,这里有很多很好的答案 Clear terminal in Python,我建议您探索一下。问题的另一部分涉及多行写作,所以我觉得这不太重复。

我认为获得所需内容的最简单方法可能是使用 f 弦并简单地执行以下操作:

import time
from datetime import datetime

while True:
    now = datetime.now()
    current_time = now.strftime("%I:%M %p")
    current_second = now.strftime("%S")
    print(f"3cClock: {current_time}\nSeconds: {current_second}")
    time.sleep(1)

如果这不能完全正常工作,您可以探索其他稍微扩展的转义码,例如 3c3[3J。不过,我已经在几个终端上成功测试了 3c

如果在查看其他问题后,您觉得这是重复的,请告诉我,我会删除这个答案,您可以关闭问题。