【问题标题】:While loop referring to timewhile循环引用时间
【发布时间】:2019-08-29 21:34:17
【问题描述】:

我遇到了关于 while 循环中时间的问题。目前这是我的代码

def autoRoutine():
    now = datetime.datetime.now().time()
    autoStart = now.replace(hour=8, minute=0)

    stoptime = datetime.datetime.now().time()
    autoStop = stoptime.replace(hour=12, minute=4)

    while (now <= autoStop):

        print("the lights are starting")
        time.sleep (1.0)
        if (now > autoStop):
            break

    print(autoStart.strftime("%H:%M"))

所以我要做的是在 autoStart 时间和 autoStop 时间之间执行 while 循环。如果是在 autoStop 之后,我希望打破 while 循环。如果有帮助,这是针对灯光例程实施的,其中灯光仅在上午 8 点(自动启动)和晚上 8 点(自动停止)之间运行,但为了等待看看它是否有效,我将 autoStop 调整为仅提前一分钟当前时间的。

我似乎无法摆脱循环,这让我发疯,因为它应该相当简单。提前致谢。

【问题讨论】:

    标签: python time while-loop


    【解决方案1】:

    我使用第三次引用来迭代我的 while 循环解决了我自己的问题

        while (keepprint == False):
    
            nowloop = datetime.datetime.now().time()
            print (nowloop)
            print (autoStop)
    
            print("the lights are starting")
            time.sleep (1.0)
            if (nowloop >= autoStop):
                keepprint = True
    

    这样我可以在每次迭代中跟踪当前时间。

    【讨论】:

      【解决方案2】:

      你应该使用一个标志:

      flag = False
      while flag = False:
          if condtion:
              flag = True
      

      Also check this file. It's a Django view but it might help you

      【讨论】:

      • 不幸的是,我仍然卡在 while 循环中。
      • 另外,链接坏了
      • 当我运行你的代码时,我得到以下输出:
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-06-20
      • 2015-12-15
      • 2013-06-22
      • 2013-01-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多