If I have a certain week number (eg 51) and a given year (eg 2008), how do I find the date of the first Monday of that same week?
Many thanks
You just need to take today's date. Then subtract the number of days which already passed this week (this gets you 'last' monday). Finally add one week to this date using a timedelta object and voila you get the next monday's date.
Calendar module is used to provide additional functions related to the calendar. In default, Monday has considered as the first day of the week in integer it's [0]and Sunday as the last day of the week[6]. In the program below . we import the calendar module.
Use the weekday() Method to Get the Name of the Day in Python. In Python, weekday() can be used to retrieve the day of the week. The datetime. today() method returns the current date, and the weekday() method returns the day of the week as an integer where Monday is indexed as 0 and Sunday is 6.
>>> import time >>> time.asctime(time.strptime('2008 50 1', '%Y %W %w')) 'Mon Dec 15 00:00:00 2008'
Assuming the first day of your week is Monday, use %U
instead of %W
if the first day of your week is Sunday. See the documentation for strptime for details.
Update: Fixed week number. The %W
directive is 0-based so week 51 would be entered as 50, not 51.
PEZ's and Gerald Kaszuba's solutions work under assumption that January 1st will always be in the first week of a given year. This assumption is not correct for ISO calendar, see Python's docs for reference. For example, in ISO calendar, week 1 of 2010 actually starts on Jan 4, and Jan 1 of 2010 is in week 53 of 2009. An ISO calendar-compatible solution:
from datetime import date, timedelta def week_start_date(year, week): d = date(year, 1, 1) delta_days = d.isoweekday() - 1 delta_weeks = week if year == d.isocalendar()[0]: delta_weeks -= 1 delta = timedelta(days=-delta_days, weeks=delta_weeks) return d + delta
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With