【问题标题】:if time exceeds x minutes如果时间超过 x 分钟
【发布时间】:2018-07-03 23:06:58
【问题描述】:

我是 python 新手,并且有一个从 json 提取数据的循环。我已经使用 if 和 else 语句设置了变量,因此当变量匹配时,它会发送通知。但是,我想在 if 中添加另一个 if 语句,以便它在窗口中显示数据,但另一个如果时间超过 5 分钟,则发送通知。

我尝试设置类似

    import time
    time = time.gmtime().tm_min
    while True:
       if price <= buy:
          print ("BUY!")
          if time > timeout:
             send message code
             timeout = time.gmtime().tm_min + 1
                if timeout > 59:
                timeout = 00

由于脚本循环运行,我认为时间必须不断更新。一旦触发了 if 语句,发送一条消息并将 5 分钟添加到 time 变量中,以便在下一个循环中,如果语句为真,如果时间未超过 5 分钟,则不要运行。我说 5 分钟,但在实际代码中我有 1 分钟,原因有两个。第一个原因是因为第一个 if 语句不会持续那么长时间。大约 30 分钟后,它离价格更远了。第二个原因是因为我不知道如何在 59 之后及时在 python 中环绕:P。

【问题讨论】:

  • 请给出一个缩进正确的工作示例。

标签: python time


【解决方案1】:

这是每次价格高于阈值时打印“BUY”的代码,如果在前 60 秒内没有发送通知,则发送通知。

import time
import random

def get_price():
    return random.random()

buy = 0.2  # Threshold price for buying
notification_time = 0   # This initial value ensures that the first notification is sent.
while True:
    if get_price() <= buy:
        print ("BUY!")
        if time.time()-notification_time > 60:
            notification_time = time.time()
            print("Sending notification")
    time.sleep(1)   # Wait 1 second before starting the next loop

尤其是在 python 中,您希望避免手动执行操作,就像您从时间对象中获取 tm_min 一样。您通常可以通过使用现有库获得更好的结果,例如两个时间戳之间的减法。

【讨论】:

  • 我还没有编写工作代码,但基本上无法弄清楚如何避免超时,这样我仍然可以每秒看到窗口中的更新,除非在发送通知之后不要发送另一个x 分钟。
  • 感谢您的澄清。我想我现在可以更新我的答案来回答你原来的问题了。
【解决方案2】:
from time import perf_counter

while True:
    start_time = perf_counter() + 300  # Set limit to 5 minutes (60 seconds * 5)

    if price <= buy:
        print ("BUY!")

    if perf_counter() > start_time:
        #send message code

【讨论】:

  • 完全可以满足我的需要!我不得不做出改变。因为它在一个循环中,它总是在更新 start_time = perf_counter() 所以它永远不会到达。通过将 start_time = perf_counter() 移动到 while true: 上方,并在 #send 消息代码之后添加 start_time = perf_counter() + 300。谢谢!!!!
猜你喜欢
  • 1970-01-01
  • 2016-10-09
  • 1970-01-01
  • 1970-01-01
  • 2017-05-06
  • 2013-07-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多