You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
29 lines
994 B
29 lines
994 B
import time
|
|
from datetime import datetime
|
|
|
|
def display_live_time():
|
|
"""
|
|
实时显示当前时间,每秒更新一次。
|
|
"""
|
|
try:
|
|
while True:
|
|
# 1. 获取当前时间
|
|
now = datetime.now()
|
|
|
|
# 2. 格式化时间为字符串 (年-月-日 时:分:秒)
|
|
current_time_str = now.strftime("%Y-%m-%d %H:%M:%S")
|
|
|
|
# 3. 打印时间。end='\r' 表示不换行,而是将光标移回行首,实现覆盖更新。
|
|
# flush=True 确保立即显示在终端。
|
|
print(f"当前时间: {current_time_str}", end="\r", flush=True)
|
|
|
|
# 4. 暂停1秒
|
|
time.sleep(1)
|
|
|
|
except KeyboardInterrupt:
|
|
# 当用户按下 Ctrl+C 时,捕获 KeyboardInterrupt 异常,
|
|
# 打印一个换行和提示信息,然后优雅地退出程序。
|
|
print("\n程序已退出。")
|
|
|
|
if __name__ == "__main__":
|
|
display_live_time() |