time.strftime
函数在 Python 中用于格式化时间。如果在 while
循环中使用时发现时间未更新,通常是因为循环的执行速度非常快,导致在短时间内多次调用 time.strftime
函数时,时间看起来没有变化。
time.strftime(format[, t])
函数根据指定的格式把一个时间元组(或 struct_time
)转化为格式化的时间字符串。如果没有指定 t
参数,则使用当前本地时间。
在 while
循环中,如果循环体执行得非常快,那么每次循环调用 time.strftime
时,可能都在同一秒内,因此显示的时间看起来没有变化。
time.sleep()
函数,使每次循环之间有一定的时间间隔。import time
while True:
current_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
print(current_time)
time.sleep(1) # 增加1秒的延迟
import time
last_time = None
while True:
current_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
if current_time != last_time:
print(current_time)
last_time = current_time
通过上述方法,可以有效解决 time.strftime
在 while
循环中未更新的问题。
领取专属 10元无门槛券
手把手带您无忧上云