Skip to content
Related Articles

Related Articles

Improve Article

Python program to get the nth weekday after a given date

  • Last Updated : 16 May, 2021

Given a date and weekday index, the task is to write a Python program to get the date for the given day of the week occurring after the given date. The weekday index is based on the below table:

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

Examples:

Input : test_date = datetime.datetime(2017, 3, 14), weekday_idx = 4

Output : 2017-03-17 

Explanation : 14 March is Tuesday, i.e 1 weekday, 4th weekday is a Friday, i.e 17 March.



Input : test_date = datetime.datetime(2017, 3, 12), weekday_idx = 5

Output : 2017-03-18

Explanation : 12 March is Sunday, i.e 6th weekday, 5th weekday in next week is a Sturday, i.e 18 March.

Method #1 : Using timedelta() + weekday()

In this, we subtract the date weekday from the weekday index and then check for required index extracted, then the required day, if negative is summed with 7 and then the resultant number is added to current date using 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])

Output:

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

Method #2 : Using lambda function

Using the lambda function provides a shorthand and compact solution to the question. 

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])

Output:

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

 Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.  

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course




My Personal Notes arrow_drop_up
Recommended Articles
Page :