如何计算该月的第一个星期一;蟒蛇3.3+

bco*_*ble 7 python date function python-3.x python-datetime

我需要在该月的第一个星期一运行月度报告并使用 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)

Run Code Online (Sandbox Code Playgroud)

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

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

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

Nic*_*ick 14

一种方法是忽略当前day值,而直接使用7; 那么你可以简单地减去weekday偏移量:

from datetime import datetime, timedelta

# note change to function signature
def find_first_monday(year, month):
    d = datetime(year, int(month), 7)
    offset = -d.weekday() # weekday == 0 means Monday
    return d + timedelta(offset)
Run Code Online (Sandbox Code Playgroud)

这可以概括为查找当月中一周中任意一天的第一天,输入dow中星期一 = 0 且星期日 = 6。例如:

def find_first_dow(year, month, dow):
    d = datetime(year, int(month), 7)
    offset = -((d.weekday() - dow) % 7)
    return d + timedelta(offset)

for i in range(7):
     find_first_day(2024, 2, i)
Run Code Online (Sandbox Code Playgroud)

输出:

datetime.datetime(2024, 2, 5, 0, 0)
datetime.datetime(2024, 2, 6, 0, 0)
datetime.datetime(2024, 2, 7, 0, 0)
datetime.datetime(2024, 2, 1, 0, 0)
datetime.datetime(2024, 2, 2, 0, 0)
datetime.datetime(2024, 2, 3, 0, 0)
datetime.datetime(2024, 2, 4, 0, 0)
Run Code Online (Sandbox Code Playgroud)