Skip to content
Related Articles

Related Articles

Save Article
Improve Article
Save Article
Like Article

Python – Get Month from year and weekday

  • Last Updated : 17 Jun, 2021

Given a year and weekday, the task is to write a Python program to get a month and the week.

Example:

 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

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, %w
from datetime import datetime, timedelta
  
# initializing year
test_year = 1997
  
# initializing week
test_week = 27
               
# printing original date
print("The original year, week is : " + str(test_year) + " " + str(test_week))
  
date = str(test_year) + '-W' + str(test_week)
  
# getting date
res = datetime.strptime(date + '-1', "%Y-W%W-%w")
  
# printing result
print("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 datetime
from dateutil.relativedelta import relativedelta
  
# initializing year
test_year = 1997
  
# initializing week
test_week = 27
               
# printing original date
print("The original year, week is : " + str(test_year) + " " + str(test_week))
  
# contructing date
date = 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 result
print("The starting date of week : " + str(res))

Output:

The original year, week is : 1997 27
The starting date of week : 1997-07-09



My Personal Notes arrow_drop_up
Recommended Articles
Page :