Python Forum
Convert calendarweek into date - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Convert calendarweek into date (/thread-27990.html)



Convert calendarweek into date - and2handles - Jun-30-2020

Hello there,

I am trying to convert a calendar week into the first and last day of that week.

So for example I am searching for the start and end date of the 24th calendar week of 2020 and the programm should tell me that the first day is the 8.06. and the last day of the week is 14.06.
Sadly the programs thinks that I mean the 24th of december 2019 and I dont know how to fix this.

My code looks as this:

from datetime import datetime, timedelta
date_y = "2020-"
date_w = "24"
date_str = date_y + date_w

date_obj = datetime.strptime(date_str, '%Y-%W')

# First day of the week
start_of_week = date_obj - timedelta(days=date_obj.weekday())  
# Last day of the week
end_of_week = start_of_week + timedelta(days=6)  

print(start_of_week)
print(end_of_week)



RE: Convert calendarweek into date - DeaD_EyE - Jun-30-2020

Calculate the week from current datetime/date:
import datetime
year, week, day = datetime.datetime.now().isocalendar()
# weekday is from 1 - 7

# converting back to datetime/date
the_date = datetime.date.fromisocalendar(year, week, day)
the_datetime = datetime.datetime.fromisocalendar(year, week, day)
Now getting for date X the start date of the week and the end date of the week:

def get_week(date_or_datetime):
    MONDAY, SUNDAY = 1, 7
    calendar = datetime.date.fromisocalendar
    year, week, _ = date_or_datetime.isocalendar()
    return calendar(year, week, MONDAY), calendar(year, week, SUNDAY)
I assigned inside the function datetime.date.fromisocalendar to calendar.
Just to keep it shorter.