给出一个'开始'日期和频率(每月,每季度,每两年,每年),我如何计算今天是否是执行所需行动的日期?
例如,开始日期是2010-01-01,频率是每月。一个cron作业每天都会运行一个Django管理命令,所以在2010-02-01,应该执行所需的操作(不管是什么,对这个问题都不重要)。
答案 0 :(得分:2)
这实际上比我原先想象的要简单。由于所有这些间隔都发生在月份上,因此计算它非常简单。它使用relativedelta
中的dateutil
对象。
from datetime import date
from dateutil.relativedelta import relativedelta
starts_at = date(2010, 1, 1)
today = date(2010, 2, 1) # as an example
diff = relativedelta(today, starts_at)
if diff.days == 0: # there must be no days difference between two dates
if diff.months % 12 == 0: # this is a year interval
do_something('annual')
elif diff.months % 6 == 0: # this is a six month interval
do_something('bi_annual')
elif diff.months % 3 == 0: # this is a three month interval
do_something('quarter')
else: # this is a month interval
do_something('month')
答案 1 :(得分:1)
有一个很棒的Delorean
library,它有相关的stops()
function。我们的想法是找出今天的日期是否是一个范围的“停止”之一。示例实施:
from datetime import datetime
import delorean
from delorean import stops
def is_it_time(start_date, frequency):
today = datetime.now()
today_date = today.date()
try:
next(stop for stop in stops(frequency, start=start_date, stop=today)
if stop.date == today_date)
return "It's time."
except StopIteration:
return "It's not the time."
print is_it_time(datetime(2010, 1, 21), delorean.MONTHLY)
print is_it_time(datetime(2010, 1, 22), delorean.MONTHLY)
打印:
It's time.
It's not the time.
请注意frequency
此处必须是Delorean
频率常量之一,但是,如果您需要自定义频率值,只需将它们适当地映射到Delorean
常量。
答案 2 :(得分:1)
要查找今天是否为重复日期,您可以使用today in recurring_rule
:
from datetime import datetime
from dateutil.rrule import rrule, MONTHLY # $ pip install python-dateutil
starts_at = datetime(2010, 1, 1)
today = datetime(2010, 2, 1)
interval = {'monthly': 1, 'quarterly': 3,
'bi-annually': 6, 'annually': 12}[frequency]
if today in rrule(MONTHLY, dtstart=starts_at, interval=interval):
print('today is a recurring date')
dateutil.rrule
可让您根据RFC 2445创建定期规则。
如果你只需要支持每月,每季度,每两年,每年频率的简单规则,这可能是一种过度杀伤,但在更复杂的情况下它可能会有用。