Python – Get Month from year and weekday
Given a year and weekday, the task is to write a Python program to get a month and the week.
Example:
Input : test_year = 1997, test_week = 27 Output : 1997-07-07 00:00:00 Explanation : 27th Week starts from 7 july in 1997. Input : test_year = 2021, test_week = 27 Output : 2021-07-05 00:00:00 Explanation : 27th Week starts from 5 july in 2021.
Method #1 : Using %W, %w
Parsing the date with %W sets us to start the week, additionally, %w gets the weekday required, we’ll use default to be 1. Can be tweaked as per requirements.
Python3
# Python3 code to demonstrate working of# Start week from year and weekday# Using %W, %wfrom datetime import datetime, timedelta # initializing yeartest_year = 1997 # initializing weektest_week = 27 # printing original dateprint("The original year, week is : " + str(test_year) + " " + str(test_week)) date = str(test_year) + '-W' + str(test_week) # getting dateres = datetime.strptime(date + '-1', "%Y-W%W-%w") # printing resultprint("The starting date of week : " + str(res)) |
Output:
The original year, week is : 1997 27 The starting date of week : 1997-07-07 00:00:00
Method #2: Using relativedelta()
This just adds required weeks to the required year and gets the initial date required. This adds weeks, hence could give any weekday depending upon the start date of the year.
Python3
# Python3 code to demonstrate working of# Start week from year and weekday# Using relativedelta()import datetimefrom dateutil.relativedelta import relativedelta # initializing yeartest_year = 1997 # initializing weektest_week = 27 # printing original dateprint("The original year, week is : " + str(test_year) + " " + str(test_week)) # contructing datedate = datetime.date(test_year, 1, 1) # getting date by adding weeks to year beg. # prints 9 July. as 1 jan was wednesday, 27th # weeks beginning is from wed.res = date + relativedelta(weeks = +test_week) # printing resultprint("The starting date of week : " + str(res)) |
Output:
The original year, week is : 1997 27 The starting date of week : 1997-07-09
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


