Python - Get Month from year and weekday
Last Updated :
17 May, 2023
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, %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))
OutputThe 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))
# constructing 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
Method #3: Using calendar module
Approach
using the calendar module to get the date of the first day of the given week in the given year. We then use the datetime module to create a datetime object with the date and time set to 0.
Algorithm
1. Import the calendar and datetime modules.
2. Use the calendar module to get the date of the first day of the given week in the given year.
3. Create a datetime object with the date and time set to 0.
4. Return the datetime object as a string with the desired format.
Python3
import calendar
import datetime
def get_month(test_year, test_week):
date_obj = datetime.datetime.strptime('{} {} 1'.format(test_year, test_week), '%Y %W %w')
return date_obj.strftime("%Y-%m-%d %H:%M:%S")
test_year = 1997
test_week = 27
print(get_month(test_year, test_week))
Output1997-07-07 00:00:00
Time complexity: O(1)
Auxiliary Space: O(1)
Approach#4: Using timedelta
The function get_date_from_week takes two inputs, the test year and the week number. It creates a datetime object for the first day of the given year. It calculates the date of the first Monday of the year by adding a timedelta to the year_start until it becomes Monday. It calculates the date of the Monday of the given week by adding a timedelta of weeks to the first Monday. It calculates the date of the Sunday of the given week by adding a timedelta of 6 days to the Monday. It returns the target_sunday as a datetime object.
Algorithm
1. Define the function get_date_from_week with two inputs test_year and test_week.
2. Create a datetime object year_start for the first day of the given year.
3. Calculate the date of the first Monday of the year by adding a timedelta to the year_start until it becomes Monday.
4. Calculate the date of the Monday of the given week by adding a timedelta of weeks to the first Monday.
5. Calculate the date of the Sunday of the given week by adding a timedelta of 6 days to the Monday.
6. Return the target_sunday as a datetime object.
Python3
from datetime import datetime, timedelta
def get_date_from_week(test_year, test_week):
# Create a datetime object for the first day of the given year
year_start = datetime(test_year, 1, 1)
# Calculate the date of the first Monday of the year
first_monday = year_start + timedelta(days=(7 - year_start.weekday()))
# Calculate the date of the Monday of the given week
target_monday = first_monday + timedelta(weeks=(test_week - 1))
# Calculate the date of the Sunday of the given week
target_sunday = target_monday + timedelta(days=6)
return target_sunday
test_year = 1997
test_week = 27
result_date = get_date_from_week(test_year, test_week)
print(result_date.strftime('%Y-%m-%d %H:%M:%S'))
Output1997-07-13 00:00:00
Time Complexity: O(1), as it performs a fixed number of operations and does not depend on the size of the input.
Auxiliary Space: O(1), as it only creates a few datetime objects and does not store any additional data.
Similar Reads
Python program to print current year, month and day
In this article, the task is to write a Python Program to print the current year, month, and day. Approach: In Python, in order to print the current date consisting of a year, month, and day, it has a module named datetime. From the DateTime module, import date classCreate an object of the date clas
1 min read
Python program to find the first day of given year
Given a year as input, write a Python to find the starting day of the given year. We will use the Python datetime library in order to solve this problem. Example: Input : 2010 Output :FridayInput :2019 Output :Tuesday Below is the implementation: Python3 # Python program to find the first day of giv
2 min read
Python program to get the nth weekday after a given date
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: IndexWeekday0Monday1Tuesday2Wednesday3Thursday4Friday5Saturday6Sunday Examples: Input : test_date = datet
3 min read
Python program to print calendar of given year
Given a valid year as input, write a Python program to print the calendar of given year. In order to do this, we can simply use calendar module provided in Python. For more details about calendar module, refer this article. Python3 1== # Python program to print calendar for given year # importing ca
3 min read
Python - Last business day of every month in year
Given a year and weekday number, the task is to write a Python program to extract each date of the month corresponding to the weekday. Input : year = 1997, weekdy = 5 Output : ['25/1/1997', '22/2/1997', '29/3/1997', '26/4/1997', '31/5/1997', '28/6/1997', '26/7/1997', '30/8/1997', '27/9/1997', '25/10
6 min read
Python Program to Count date on a particular weekday in given range of Years
Given a date, our task is to get the weekday index and year range, and compute the total occurrence of the date on a particular weekday in the year range. Example: Input : date = 13, weekdy = 5, strt, end = 1950, 2020Output : 120Explanation : Total dates with Friday 13 from 1950 - 2020 is 120. Input
5 min read
Python program to Get Month Name from Month Number
Given a datetime object or month number, the task is to write a Python program to get the corresponding month name from it. Examples: Input : test_date = datetime(2020, 4, 8)Output : AprilExplanation : 4th Month is April. Input : test_date = datetime(2020, 1, 8)Output : JanuaryExplanation : 1st Mont
4 min read
Python program to calculate age in year
Given birth date in y/m/d format, write a Python program to find the present age in years. Examples: Input : 1997/2/3 Output : 21 years (for present year i.e 2018) Input : 2010/12/25 Output : 8 years (for present year i.e 2018) Approach # 1: The naive approach to find the current age in years is to
4 min read
Python program to find day of the week for a given date
Write a Python program to extract weekdays from a given date for any particular date in the past or future. Let the input be in the format "dd mm yyyy". Example Input : 03 02 1997 Output : MondayInput : 31 01 2019Output : ThursdayThe already discussed approach to extract weekdays from a given date f
6 min read
Python - Get Most recent previous business day
Given a date, the task is to write a Python program to get the most recent previous business day from the given date. Example: Input : test_date = datetime(2020, 1, 31) Output : 2020-01-30 00:00:00 Explanation : 31 Jan 2020, being a Friday, last business day is thursday, i.e 30 January. Input : test
4 min read