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


当前回答

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

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

其他回答

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

我相信date. iscalendar()将是答案。本文解释了ISO 8601日历背后的数学原理。查看Python文档的datetime页面的date. iscalendar()部分。

>>> dt = datetime.date(2010, 6, 16) 
>>> wk = dt.isocalendar()[1]
24

. iscalendar()返回一个三元组,包含(年,星期数,星期天数)。dt. iscalendar()[0]返回年份,dt. iscalendar()[1]返回周数,dt. iscalendar()[2]返回周数。尽可能的简单。

您可以直接从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中对我有效

如果你只使用等历法周数,那么以下内容就足够了:

import datetime
week = date(year=2014, month=1, day=1).isocalendar()[1]

这将检索由iscalendar为周数返回的元组的第二个成员。

但是,如果您打算使用处理公历的日期函数,那么单独使用iscalendar是行不通的!举个例子:

import datetime
date = datetime.datetime.strptime("2014-1-1", "%Y-%W-%w")
week = date.isocalendar()[1]

这里的字符串表示返回2014年第一周的星期一作为日期。当我们使用iscalendar在这里检索周数时,我们希望得到相同的周数,但我们没有。相反,我们得到的周数是2。为什么?

公历的第一周是包含星期一的第一周。等日历中的第1周是包含星期四的第一周。2014年初的部分周包含一个星期四,所以这是等历的第一周,日期是第2周。

如果我们想要得到公历周,我们将需要从等历法转换为公历。下面是一个简单的函数。

import datetime

def gregorian_week(date):
    # The isocalendar week for this date
    iso_week = date.isocalendar()[1]

    # The baseline Gregorian date for the beginning of our date's year
    base_greg = datetime.datetime.strptime('%d-1-1' % date.year, "%Y-%W-%w")

    # If the isocalendar week for this date is not 1, we need to 
    # decrement the iso_week by 1 to get the Gregorian week number
    return iso_week if base_greg.isocalendar()[1] == 1 else iso_week - 1

我将讨论总结为两个步骤:

将原始格式转换为datetime对象。 使用datetime对象或date对象的函数来计算周数。

热身

from datetime import datetime, date, time
d = date(2005, 7, 14)
t = time(12, 30)
dt = datetime.combine(d, t)
print(dt)

第一步

要手动生成一个datetime对象,可以使用datetime.datetime(2017,5,3)或datetime.datetime.now()。

但实际上,我们通常需要解析一个现有的字符串。我们可以使用strptime函数,例如datetime.strptime('2017-5-3','%Y-%m-%d'),其中必须指定格式。不同格式代码的详细信息可以在官方文档中找到。

或者,更方便的方法是使用dateparse模块。例如dateparser。parse('16 Jun 2010'), dateparser.parse('12/2/12')或dateparser.parse('2017-5-3')

以上两种方法将返回一个datetime对象。

第二步

使用获得的datetime对象调用strptime(format)。例如,

python

dt = datetime.strptime('2017-01-1','%Y-%m-%d') # return a datetime object. This day is Sunday
print(dt.strftime("%W")) # '00' Monday as the 1st day of the week. All days in a new year preceding the 1st Monday are considered to be in week 0.
print(dt.strftime("%U")) # '01' Sunday as the 1st day of the week. All days in a new year preceding the 1st Sunday are considered to be in week 0.
print(dt.strftime("%V")) # '52' Monday as the 1st day of the week. Week 01 is the week containing Jan 4.

决定使用哪种格式是很棘手的。更好的方法是获取一个日期对象来调用iscalendar()。例如,

python

dt = datetime.strptime('2017-01-1','%Y-%m-%d') # return a datetime object
d = dt.date() # convert to a date object. equivalent to d = date(2017,1,1), but date.strptime() don't have the parse function
year, week, weekday = d.isocalendar() 
print(year, week, weekday) # (2016,52,7) in the ISO standard

实际上,您更有可能使用date. iscalendar()来准备周报,特别是在圣诞节-新年购物季。