首页 > 解决方案 > Python的日期时间在特定时间范围内工作

问题描述

我有一个执行程序,可以根据用户指定的内容执行电话。
我只想在一天中的特定时间范围内安排时间,例如从上午 8 点到下午 6 点。
执行者每天 24 小时工作,正在检查数据库中的记录是否执行电话呼叫。
是否有任何棘手的方法可以通过使用 python 来安排未来的通话,并以给定的频率和通话次数datetime以某种方式设置这些工作时间。
例如,我想安排 4 次通话,频率为 1 小时。假设现在是下午 4 点。下一次通话应安排在下午 4 点、下午 5 点和下一个 - 第二天上午 8 点、上午 10 点。
我希望datetime在这种情况下工作,如下所示:

def schedule(no_of_calls: int, frequency: timedelta):
  dt = get_a_magic_datetime_with_hour_range()
  value = dt.now()  # this will get 4PM in above's example. Though if it would be 10PM it would return 8AM next day.
  for i in range(no_of_calls):
    save_to_db(value)
    value += frequency    

我知道我可以创建自己的working_datetime,这将在工作时间范围内进行适当的验证并返回值,但也许已经有类似的东西了。

如果您仍然不明白 - 想想停车计时器之类的 - 如果您在付款时间之外付款 - 它将从第二天的付款时间开始计算(如果超过 12 点,则相同)。

标签: pythonpython-datetime

解决方案


代码应该足够不言自明:除了从 2020 年 1 月 20 日星期一开始,每天早上 8 点、上午 9 点……下午 5 点,它什么都不做。

请注意,我没有对其进行测试,但至少在原则上该策略应该是可行的。我检查了各种if条件和更新规则,但在启动像这样的无限循环之前再次检查它们。

#!/usr/bin/env python

'''
This code performs a certain (generic) action
every hour, from 8 AM to 5 PM of everyday, starting
from next monday, that is 20 Jan 2020.

This means the code performs 10 actions per day
and then does nothing for the next 14 hours.

Temporal precision is seconds.
'''

import time
from datetime import datetime

str_begin = 'Jan 20 08:00:00 +0000 2020'
next_action = int(datetime.timestamp(datetime.strptime(str_begin, '%b %d %H:%M:%S %z %Y')))  # Unix timestamp


one_hour = 3600                         # Number of seconds in an hour
waiting_time = 14 * one_hour

daily_count = 0

now = int(datetime.timestamp(datetime.now()))
while True:
    if now == next_action:

        # Make a call or whatever

        daily_count += 1
        if daily_count < 10:
            next_action += one_hour
        if daily_count == 10:              # At 5 PM daily_count will be 10 and next_action will be 6 PM. You reset the count and next_action to 8 AM.
            daily_count = 0
            next_action += waiting_time

    now = int(datetime.timestamp(datetime.now()))


推荐阅读