在python中使用日期获取周数

2024-09-30 06:21:41 发布

您现在位置:Python中文网/ 问答频道 /正文

日期是datetime.date(2013, 12, 30)

我想用

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

我得到的输出是

1

为什么我没有得到去年的周数,而是得到今年的周数?

我在这里做错什么了?


Tags: importdatetimedate周数isocalendar
2条回答
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)

手动或将日期读取为字符串并获取周数,使用不同格式播放。

你没有做错什么,2013/12/30在2014年的第一周,根据ISO8601 week numbering standard

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

那一周的星期四是2014年1月2日。

其他解释该定义的方法,来自同一篇链接的维基百科文章:

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

如果您要查找给定年份的最后一周(52或53,具体取决于年份),我将使用12月28日,它始终保证在最后一周内(因为1月4日始终是下一年第一周的一部分):

def lastweeknumber(year):
    return datetime.date(year, 12, 28).isocalendar()[1]

相关问题 更多 >

    热门问题