【问题标题】:Issues with a looping python clock循环 python 时钟的问题
【发布时间】:2020-07-29 14:34:14
【问题描述】:

我正在制作一个时钟,它可以连续循环显示英国和佛罗里达州的时间,但是当我运行代码时,它只显示我开始运行代码的时间。

请记住,这是我的第一个项目。所以任何业余技巧也会有所帮助

代码本身:

#UK Time    
from datetime import datetime

now = datetime.now()

current_time = now.strftime("%H:%M:%S")

#Florida time

from datetime import timedelta

minus_hours = now - timedelta(hours=5)

display_minus_hours = minus_hours.strftime("%H:%M:%S")

while True:
    print('UK =', current_time)
    print('Florida =', display_minus_hours)

【问题讨论】:

  • 您必须再次致电datetime.now
  • 循环内的代码不会更新变量,所以当然会一遍又一遍地显示相同的值。
  • 您需要在循环中更新current_timedisplay_minus_hours 的值。 T_T
  • 欢迎来到 Stack Overflow。如果它回答了您的问题,请不要忘记接受答案(勾选答案旁边的复选标记)。这样,您的问题就不会在搜索中显示为未回答。还投票赞成好的答案。另请注意,接受和赞成答案是在 Stack Overflow 上说 thanks 的方式(不要为此使用 cmets)。既然您从这里开始,请使用tour,阅读what's on-topic,并查看How to Ask a Good Question

标签: python time clock


【解决方案1】:

你需要在循环中更新你的变量。

from datetime import datetime, timedelta


while True:
    # UK Time
    now = datetime.now()
    current_time = now.strftime("%H:%M:%S")
    # Florida time
    minus_hours = now - timedelta(hours=5)
    display_minus_hours = minus_hours.strftime("%H:%M:%S")
    
    print('UK =', current_time)
    print('Florida =', display_minus_hours)

附言这会在不改变的情况下打印出很多东西,考虑添加time.sleep(1)

【讨论】:

  • 非常感谢,这正是它所需要的,是的,我正在添加 time.sleep(1)
【解决方案2】:

问题是变量只赋值一次。

var = datetime.now()
while True:
    print(var)

您需要在每次迭代时更新变量。

while True:
    var = datetime.now()
    print(var)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-26
    相关资源
    最近更新 更多