📜  Python程序获取给定日期后的第n个工作日

📅  最后修改于: 2022-05-13 01:54:48.707000             🧑  作者: Mango

Python程序获取给定日期后的第n个工作日

给定一个日期和工作日索引,任务是编写一个Python程序来获取给定日期之后的给定星期几的日期。工作日指数基于下表:

IndexWeekday
0Monday
1Tuesday
2Wednesday
3Thursday
4Friday
5Saturday
6Sunday

例子:

方法 #1:使用timedelta() + weekday()

在这种情况下,我们从工作日索引中减去日期工作日,然后检查提取的所需索引,然后检查所需的日期,如果负数与 7 相加,然后使用 timedelta() 将所得数字添加到当前日期。

Python3
# Python3 code to demonstrate working of
# Next weekday from Date
# Using timedelta() + weekday()
import datetime
  
# initializing dates
test_date = datetime.datetime(2017, 3, 14)
  
# printing original date
print("The original date is : " + str(test_date)[:10])
  
# initializing weekday index
weekday_idx = 4
  
# computing delta days
days_delta = weekday_idx - test_date.weekday()
if days_delta <= 0:
    days_delta += 7
  
# adding days to required result
res = test_date + datetime.timedelta(days_delta)
  
# printing result
print("Next date of required weekday : " + str(res)[:10])


Python3
# Python3 code to demonstrate working of
# Next weekday from Date
# Using lamnda function
import datetime
  
# initializing dates
test_date = datetime.datetime(2017, 3, 14)
  
# printing original date
print("The original date is : " + str(test_date)[:10])
  
# initializing weekday index
weekday_idx = 4
  
# lambda function provides one liner shorthand
def lfnc(test_date, weekday_idx): return test_date + \
    datetime.timedelta(days=(weekday_idx - test_date.weekday() + 7) % 7)
  
  
res = lfnc(test_date, weekday_idx)
  
# printing result
print("Next date of required weekday : " + str(res)[:10])


输出:

The original date is : 2017-03-14
Next date of required weekday : 2017-03-17

方法 #2:使用lambda函数

使用 lambda函数为该问题提供了一种简明而紧凑的解决方案。

蟒蛇3

# Python3 code to demonstrate working of
# Next weekday from Date
# Using lamnda function
import datetime
  
# initializing dates
test_date = datetime.datetime(2017, 3, 14)
  
# printing original date
print("The original date is : " + str(test_date)[:10])
  
# initializing weekday index
weekday_idx = 4
  
# lambda function provides one liner shorthand
def lfnc(test_date, weekday_idx): return test_date + \
    datetime.timedelta(days=(weekday_idx - test_date.weekday() + 7) % 7)
  
  
res = lfnc(test_date, weekday_idx)
  
# printing result
print("Next date of required weekday : " + str(res)[:10])

输出:

The original date is : 2017-03-14
Next date of required weekday : 2017-03-17