置于循环中时如何使datetime.now函数更新

时间:2018-11-12 12:07:11

标签: python python-3.x

我创建了一个for循环,该代码将这段代码重复100次,问题是datetime导入不会在循环内更新。

以下代码:

from datetime import datetime
now = datetime.now()

print("%02d-%02d-%04d") % (now.year, now.month, now.day)
#below is the loop
for i in range(0, 100):
  time.sleep(1)
  print ("%02d:%02d:%02d") % (now.hour, now.minute, now.second)

输出的所有内容与我第一次按下run时相同的小时,分​​钟和秒。

Output below:

11:59:0711:59:07

11:59:0711:59:07

(这会进行100次)

3 个答案:

答案 0 :(得分:2)

您必须再次致电now

for i in range(0, 100):
  time.sleep(1)
  now = datetime.now()
  print ("%02d:%02d:%02d") % (now.hour, now.minute, now.second)

now是一个对象,使用时不会获得新的时间(这很糟糕)。

答案 1 :(得分:0)

您仅一次采样now,您需要像这样在for循环内进行采样

from datetime import datetime
now = datetime.now()

print("%02d-%02d-%04d") % (now.year, now.month, now.day)
#below is the loop
for i in range(0, 100):
  time.sleep(1)
  now = datetime.now()
  print ("%02d:%02d:%02d") % (now.hour, now.minute, now.second)

答案 2 :(得分:0)

为什么不在循环中移动now = datetime.now()?

for i in range(0,100):
    time.sleep(1)
    now = datetime.now()
    print ("%02d:%02d:%02d") % (now.hour, now.minute, now.second)