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

时间:2021-05-04 03:19:56

标签: python python-3.x function date python-datetime

我需要在每个月的第一个星期一运行月度报告,并用 Python 计算这一天。到目前为止,我拥有的代码将进入我们 ETL 程序中的一个模块,并确定日期是否实际上是该月的第一天。理想情况下,我需要的是如果星期一是本月的第一个星期一,则仅在这一天运行报告(执行 = 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)。如果“今天”是本月的第一个星期一,我不确定这是否会实际运行,因为它会为“今天”中传递的任何日期打印下一个星期一。

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

1 个答案:

答案 0 :(得分:1)

一种方法是忽略传入的 Column( crossAxisAlignment : CrossAxisAlignment.start, children: <Widget> [ Text('Gender:'), InputDecorator( decoration: InputDecoration( border: OutlineInputBorder(borderRadius: BorderRadius.circular(5.0)), contentPadding: EdgeInsets.all(10), ), child: DropdownButtonHideUnderline( child: DropdownButton<String>( value: gender, isDense: true, isExpanded: true, items: [ DropdownMenuItem(child: Text("Select Gender"), value: ""), DropdownMenuItem(child: Text("Male"), value: "Male"), DropdownMenuItem(child: Text("Female"), value: "Female"), ], onChanged: (newValue) { setState(() { }); }, ), ), ), ] ), 值,而只使用 day;那么你可以简单地减去 7 偏移量:

weekday