如果时间超过x分钟

时间:2018-01-24 19:37:26

标签: python time

我是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分钟,以便在下一个循环中如果该语句为真,则在时间未超过5分钟时不运行。我说5分钟,但在实际代码中我有1分钟,原因有两个。第一个原因是因为第一个if语句不会持续那么久。大约30分钟后它离价格更远了。第二个原因是因为我不知道如何在59后赶上python:P。

2 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:0)

这是打印&#34;购买&#34;的代码。每次价格高于阈值时,如果在过去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一样。通常可以使用现有库获得更好的结果,例如在两个时间戳之间减去。