Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get week number using date in python

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 ?

like image 713
Nishant Nawarkhede Avatar asked Nov 16 '25 00:11

Nishant Nawarkhede


1 Answers

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]
like image 78
Martijn Pieters Avatar answered Nov 17 '25 22:11

Martijn Pieters



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!