Get week number using date in python

◇◆丶佛笑我妖孽 提交于 2019-12-06 08:17:14

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]
from datetime import date
from datetime import datetime
ndate='10/1/2016'
ndate = datetime.strptime(ndate, '%m/%d/%Y').strftime('%Y,%m,%d')
print('new format:',ndate)
d=ndate.split(',')
wkno = date(int(d[0]),int(d[1]),int(d[2])).isocalendar()[1]
print(wkno)

manually or read a date to a string and get the week number, play around with different formats.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!