diff --git a/zbw.py b/zbw.py index e69de29..defcd9b 100644 --- a/zbw.py +++ b/zbw.py @@ -0,0 +1,29 @@ +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() \ No newline at end of file