【问题标题】:How to calculate the first Monday of the month; python 3.3+如何计算每月的第一个星期一;蟒蛇3.3+
【发布时间】:2021-07-26 10:07:09
【问题描述】:

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

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

【问题讨论】:

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


    【解决方案1】:

    一种方法是忽略传入的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)
    

    【讨论】:

      猜你喜欢
      • 2014-05-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多