Get week number using date in python

21,317

You are doing nothing wrong, 2013/12/30 falls in week 1 of 2014, according to the ISO8601 week numbering standard:

The ISO 8601 definition for week 01 is the week with the year's first Thursday in it.

The Thursday in that week is 2014/01/02.

Other ways to explain the definition, from the same linked WikiPedia article:

  • It is the first week with a majority (four or more) of its days in January (ISO weeks start on Monday)
  • Its first day is the Monday nearest to 1 January.
  • It has 4 January in it. Hence the earliest possible dates are 29 December through 4 January, the latest 4 through 10 January.
  • It has the year's first working day in it, if Saturdays, Sundays and 1 January are not working days.

If you were looking for the last week number of a given year (52 or 53, depending on the year), I'd use December 28th, which is always guaranteed to be in the last week (because January 4th is always part of the first week of the next year):

def lastweeknumber(year):
    return datetime.date(year, 12, 28).isocalendar()[1]
Share:
21,317
Nishant Nawarkhede
Author by

Nishant Nawarkhede

Working on chatbot developement.

Updated on November 01, 2020

Comments

  • Nishant Nawarkhede
    Nishant Nawarkhede over 3 years

    Date is datetime.date(2013, 12, 30)

    I am trying to get week number using

    import datetime
    datetime.date(2013, 12, 30).isocalendar()[1]
    

    I am getting output as ,

    1
    

    Why i am not getting week number of last year , instead i am getting week number of current year?

    Whats wrong i am doing here ?

  • Nishant Nawarkhede
    Nishant Nawarkhede over 10 years
    Thanks , Then how can i get last week number using this method?
  • Martijn Pieters
    Martijn Pieters over 10 years
    @Nishant: You mean you want 52, the last full week in 2013? I'll update.
  • Martijn Pieters
    Martijn Pieters over 10 years
    @Nishant: Sorry, my brain didn't kick in sooner, the last revision is the best one to determine the last week number of a year.
  • MarianD
    MarianD over 7 years
    The question was: "Why i am not getting week number of last year , instead i am getting week number of current year? Whats wrong i am doing here ?"
  • Arun Tom
    Arun Tom over 7 years
    It's supposed to be the first week of 2014 till Jan 4th
  • MarianD
    MarianD over 7 years
    I didn't comment your code but that your answer didn't hit the target - the code is done, what's wrong with its output?