Bottom Page

Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
 Convert calendarweek into date
#1
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)
Quote
#2
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.
My code examples are always for Python >=3.6.0
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
Quote

Top Page

Possibly Related Threads...
Thread Author Replies Views Last Post
  Convert weekly sequences to date and time. SinPy 0 205 Nov-23-2019, 05:20 PM
Last Post: SinPy
  convert strings of date to datetime exported from CSV GiorgosPap31 1 483 Oct-31-2019, 02:37 PM
Last Post: buran
  Substracting today's date from a date in column of dates to get an integer value firebird 1 477 Jul-04-2019, 06:54 PM
Last Post: Axel_Erfurt
  How to change existing date to current date in a filename? shankar455 1 582 Apr-17-2019, 01:53 PM
Last Post: snippsat
  Help Convert difference between inputted date and now aspeniii 1 747 Nov-30-2018, 07:31 PM
Last Post: micseydel
  Date format conversion "/Date(158889600000)/" lbitten 2 625 Nov-29-2018, 02:14 PM
Last Post: Larz60+
  Convert text file date into specific format jacklee26 11 3,292 May-15-2018, 07:36 AM
Last Post: buran
  convert date input to seconds student001 2 1,681 Mar-24-2017, 04:49 PM
Last Post: nilamo

Forum Jump:


Users browsing this thread: 1 Guest(s)