首页 > 解决方案 > 创建一个for循环,在python中每隔x时间调用一个函数

问题描述

我有这个数据:

granularity: 1h
start_time: 2021-4-28T1:1:1.342380Z
end_time: 2021-4-29T1:1:1.342360Z

我想创建一个像这样的伪代码:

for start_time to end_time:
    call function on each interval of granularity

在给定的示例中,我将从 start_time 到 end_time 每 1 小时调用一次函数。时间和粒度参数可以更改,并且不固定为我的示例中给出的值。它可以是 60 分钟,5 秒...

经过一番思考并在博客和 Stack Overflow 上进行搜索后,我无法得出如何做的结论。有任何想法吗?

谢谢!!

标签: python-3.xfor-looptime

解决方案


我使用 datetime 库编写了这个,它是大多数 python 安装的标准。它需要以秒为单位的时间,因此,60 秒为一分钟,3600 秒为一小时。希望这对您有所帮助,并且是您正在寻找的东西,祝您编码愉快!


:编辑:OP纠正了我,它需要一个开始和结束时间,我去了并添加了它。

:新代码:V

from datetime import datetime

def alert(time):
    hourtime = time / 60
    print(f"It's Been {time} seconds or {hourtime} Hours")


def timer(seconds, start_time, end_time):
    curr_time = datetime.now()
    formatted_time = curr_time.strftime('%S')
    lasttime = formatted_time
    localtimer = 0 
    while True:
        curr_time = datetime.now()

        formatted_time = curr_time.strftime('%S')
        time_ =  curr_time.strftime('%H%M')


        if int(time_) <= int(end_time) - 1: # Check to see if the current time is less than the end time
            if int(time_) >= int(start_time): # check to see if it's Greater or equal to the start time
                if int(lasttime) != int(formatted_time): # if so it does the alert function every x seconds
                    lasttime = formatted_time
                    print(localtimer) # You can Keep or remove this line it's just for counting how many seconds have gone by.
                    localtimer += 1
                if localtimer == int(seconds):
                    alert(seconds)
                    localtimer = 0
        

timer(seconds=5, start_time=1547, end_time=1548) # It takes time in seconds, start and end time are both in the 24 hr format just without the ":" so instead of 15:44, it would be 1544


这是没有开始和结束时间的旧代码

from datetime import datetime

def alert(time):
    hourtime = time / 60
    print(f"It's Been {time} seconds or {hourtime} Hours")


def timer(seconds):
    curr_time = datetime.now()
    formatted_time = curr_time.strftime('%S')
    lasttime = formatted_time
    localtimer = 0 
    while True:
        curr_time = datetime.now()
        formatted_time = curr_time.strftime('%S')
        if int(lasttime) != int(formatted_time):
            lasttime = formatted_time
            print(localtimer) # You can Keep or remove this line it's just for counting how many seconds have gone by.
            localtimer += 1
        if localtimer == int(seconds):
            alert(seconds)
            localtimer = 0


timer(5) # It takes time in seconds so 3600 will be 3600 seconds which is an hour and 5 is 5 seconds, so a minute would be 60 and so on and so forth

推荐阅读