如何用Python找出今年6月16日(wk24)的周数?


当前回答

您可以直接从datetime作为字符串获取周数。

>>> import datetime
>>> datetime.date(2010, 6, 16).strftime("%V")
'24'

你也可以得到不同的“类型”的周数的年份改变strftime参数:

%U - Week number of the year (Sunday as the first day of the week) as a zero padded decimal number. All days in a new year preceding the first Sunday are considered to be in week 0. Examples: 00, 01, …, 53 %W - Week number of the year (Monday as the first day of the week) as a decimal number. All days in a new year preceding the first Monday are considered to be in week 0. Examples: 00, 01, …, 53 [...] (Added in Python 3.6, backported to some distribution's Python 2.7's) Several additional directives not required by the C89 standard are included for convenience. These parameters all correspond to ISO 8601 date values. These may not be available on all platforms when used with the strftime() method. [...] %V - ISO 8601 week as a decimal number with Monday as the first day of the week. Week 01 is the week containing Jan 4. Examples: 01, 02, …, 53 from: datetime — Basic date and time types — Python 3.7.3 documentation

我是从这里知道的。它在Python 2.7.6中对我有效

其他回答

datetime。Date有一个iscalendar()方法,它返回一个包含日历周的元组:

>>> import datetime
>>> datetime.date(2010, 6, 16).isocalendar()[1]
24

datetime.date. iscalendar()是一个实例方法,返回一个元组,其中包含给定日期实例的年份、周号和星期。

在Python 3.9+中,iscalendar()返回一个包含年份、星期和星期的命名元组,这意味着您可以使用命名属性显式地访问星期:

>>> import datetime
>>> datetime.date(2010, 6, 16).isocalendar().week
24

已经给出了很多答案,但我想补充一下。

如果您需要将周显示为年/周样式(例如,1953 - 2019年第53周,2001 - 2020年第1周等),您可以这样做:

import datetime

year = datetime.datetime.now()
week_num = datetime.date(year.year, year.month, year.day).strftime("%V")
long_week_num = str(year.year)[0:2] + str(week_num)

它将使用当前的年份和周,写这篇文章当天的long_week_num将是:

>>> 2006

这是另一个选择:

import time
from time import gmtime, strftime
d = time.strptime("16 Jun 2010", "%d %b %Y")
print(strftime(d, '%U'))

结果是24。

见:http://docs.python.org/library/datetime.html strftime-and-strptime-behavior

一般要获取当前周数(从周日开始):

from datetime import *
today = datetime.today()
print today.strftime("%U")

对于pandas用户,如果你想获得一列周数:

df['weekofyear'] = df['Date'].dt.week