如何计算每月的第一个星期一; python 3.3+

How to calculate the first Monday of the month; python 3.3+

我需要在每个月的第一个星期一运行做月报,并用Python计算这一天。到目前为止,我的代码将进入我们的 ETL 程序中的一个模块,并将确定日期是否实际上是该月的第一天。理想情况下,我需要的是如果星期一是该月的第一个星期一,运行 仅在这一天报告 (execute = 1)。否则,不要 运行 任何东西(execute = 0)。我有:

# Calculate first Monday of the month

# import module(s)

from datetime import datetime, date, timedelta

today = date.today() # - timedelta(days = 1)
datee = datetime.strptime(str(today), "%Y-%m-%d")

print(f'Today: {today}')

# function finds first Monday of the month given the date passed in "today"

def find_first_monday(year, month, day):
    d = datetime(year, int(month), int(day))
    offset = 0-d.weekday() #weekday = 0 means monday
    if offset < 0:
        offset+=7
    return d+timedelta(offset)

# converts datetime object to date
first_monday_of_month = find_first_monday(datee.year, datee.month, datee.day).date()

# prints the next Monday given the date that is passed as "today" 

print(f'Today\'s date: {today}')
print(f'First Monday of the month date: {first_monday_of_month}')

# if first Monday is true, execute = 1, else execute = 0; 1 will execute the next module of code

if today == first_monday_of_month:
  execute = 1
  print(execute) 
else:
  execute = 0
  print(execute)

假设“今天”中的日期不在该月的第一个星期一之后,它就可以工作。当“今天”在该月的第一个星期一之后,它会打印下一个星期一。

我们的 ETL 调度程序允许我们每天、每周或每月 运行。我想我每天都必须 运行,即使这是月度报告,带有此代码的模块将确定“今天”是否是该月的第一个星期一。如果不是第一个星期一,则不会执行下一个代码模块(execute = 0)。如果“今天”是该月的第一个星期一,我不确定这实际上会 运行,因为它会为“今天”中传递的任何日期打印下一个星期一。

我似乎找不到我需要的答案来确保它只计算每月的第一个星期一并且只计算 运行 那天的报告。提前致谢。

一种方法是忽略传入的 day 值,而只使用 7 代替;那么你可以简单地减去 weekday 偏移量:

def find_first_monday(year, month, day):
    d = datetime(year, int(month), 7)
    offset = -d.weekday() #weekday = 0 means monday
    return d + timedelta(offset)

一种略有不同的方法 - date.weekday() function 为您提供了星期几的索引(其中星期一为 0,星期日为 6)。您可以使用此值直接计算一周中的任何一天将落在哪一天。对于星期一,像这样...

def first_monday(year, month):
    day = (8 - datetime.date(year, month, 1).weekday()) % 7
    return datetime.date(year, month, day)

当然,您可以制作一个通用版本,让您可以指定一周中的哪一天,如下所示:

def first_dow(year, month, dow):
    day = ((8 + dow) - datetime.date(year, month, 1).weekday()) % 7
    return datetime.date(year, month, day)

它接受与 date.weekday() 函数 returns 相同的索引(星期一为 0,星期日为 6)。例如,要查找 2022 年 7 月的第一个星期三 (2)...

>>> first_dow(2022, 7, 2)
datetime.date(2022, 7, 6)