Sunday, November 17, 2024
Google search engine
HomeLanguagesPython – Get Month from year and weekday

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, %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))
 
# 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))


Output

1997-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'))


Output

1997-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.

RELATED ARTICLES

Most Popular

Recent Comments