0

I am trying to identify the month number from a given week and year number (both are user inputs). The script needs to be written in python. eg - 1) Yr 2017, Wk 12 results in Month# 3 2) Yr 2017, Wk 32 results in Month#8 and so on

I am a newbie and searched for all date time examples, still no clue. Any ideas? Would really appreciate the help. Thanks in advance!

achal
  • 11
  • 3
  • What month do you want if the week spans two months? For example, year 2017, week 5 (January 30, 2017 - February 5, 2017). – Robᵩ Oct 02 '17 at 04:30
  • Related questions: https://stackoverflow.com/questions/304256/whats-the-best-way-to-find-the-inverse-of-datetime-isocalendar https://stackoverflow.com/questions/17087314/get-date-from-week-number – Robᵩ Oct 02 '17 at 04:37
  • which week numbering scheme? (iso?) – thebjorn Oct 02 '17 at 05:30
  • Good question Rob. If I use iso scheme for calendar, will this still matter? – achal Oct 02 '17 at 06:06

1 Answers1

0

As we know the numbers of days in each month of a given year, and the number of days that span w weeks (w*7) it is sufficient to sum the days of each month until the result is greater than w*7, counting the number of months used in the sum. If we used say n months, the number you want is n

We can know if the year is a leap year as the following demonstrates.

import calendar
print calendar.isleap(2017)
Odo Frodo
  • 26
  • 3
  • What if the Wk1 has only 1 week? Does this still apply? – achal Oct 02 '17 at 05:18
  • Allow me to correct myself. The number you want is n. I shall update my answer. – Odo Frodo Oct 02 '17 at 05:32
  • So if you want the month of week 1, the sum would halt on the first month (as 30>7*1), so week 1 belongs to month 1. – Odo Frodo Oct 02 '17 at 05:34
  • Note that this assumes that we want the number of the month that contains the last day of the given week. As Rob commented the behaviour you expect when a week is part of two months is not specified. – Odo Frodo Oct 02 '17 at 05:38