Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Python, how do I find the date of the first Monday of a given week?

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

like image 702
Rui Vieira Avatar asked Dec 29 '08 00:12

Rui Vieira


People also ask

How do you get the next Monday date in Python?

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.

How do I get the first Sunday of the month in Python?

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.

How do I return the day of the week in Python?

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.


2 Answers

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

like image 95
Robert Gamble Avatar answered Sep 26 '22 00:09

Robert Gamble


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 
like image 31
Vaidas K. Avatar answered Sep 24 '22 00:09

Vaidas K.