定时刷新显示时间

定时刷新显示时间#

import asyncio
import datetime

async def display_date(time_s_end: float = 5.0, delay: float = 1.0):
    """每隔 delay 秒刷新显示当前日期,直至 time_s_end 秒终止"""
    loop = asyncio.get_running_loop()
    end_time = loop.time() + time_s_end
    while 1:
        print(datetime.datetime.now())
        if (loop.time() + delay) >= end_time:
            break
        await asyncio.sleep(1)
await display_date(5)
2024-11-09 17:19:47.116832
2024-11-09 17:19:48.118124
2024-11-09 17:19:49.119406
2024-11-09 17:19:50.120694
2024-11-09 17:19:51.121978