You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何让Python函数每次调用时输出更新后的时间?

问题解决思路

你的代码里local_time是在函数执行前就计算好的固定值,循环中只是重复打印这个初始值,自然不会更新。要实现每次打印最新时间,只需要在每次循环时重新获取当前时间即可,有两种简单的实现方式:

方法一:循环内直接获取最新时间

直接在循环里调用time.ctime()(该方法默认使用当前时间的时间戳,无需手动调用time.time()),每次打印都会拿到最新时间:

import time

print("Start Time:", time.ctime())
def bot():
    x = 0
    while x < 16:
        time.sleep(1)
        # 每次循环重新获取当前时间
        print("Time:", time.ctime())
        x += 1

bot()

方法二:封装获取时间的函数(便于复用)

如果后续需要多次获取当前时间,可以把获取逻辑封装成函数,每次调用都返回最新时间:

import time

def get_current_time():
    return time.ctime()

print("Start Time:", get_current_time())
def bot():
    x = 0
    while x < 16:
        time.sleep(1)
        print("Time:", get_current_time())
        x += 1

bot()

内容的提问来源于stack exchange,提问作者iminertia

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.25 23:39:22