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


当前回答

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

将原始格式转换为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()来准备周报,特别是在圣诞节-新年购物季。

其他回答

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

iscalendar()对于某些日期返回错误的年和周数值:

Python 2.7.3 (default, Feb 27 2014, 19:58:35) 
[GCC 4.6.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import datetime as dt
>>> myDateTime = dt.datetime.strptime("20141229T000000.000Z",'%Y%m%dT%H%M%S.%fZ')
>>> yr,weekNumber,weekDay = myDateTime.isocalendar()
>>> print "Year is " + str(yr) + ", weekNumber is " + str(weekNumber)
Year is 2015, weekNumber is 1

与Mark Ransom的方法相比:

>>> yr = myDateTime.year
>>> weekNumber = ((myDateTime - dt.datetime(yr,1,1)).days/7) + 1
>>> print "Year is " + str(yr) + ", weekNumber is " + str(weekNumber)
Year is 2014, weekNumber is 52

如果你想改变一周的第一天,你可以使用日历模块。

import calendar
import datetime

calendar.setfirstweekday(calendar.WEDNESDAY)
isodate = datetime.datetime.strptime(sweek,"%Y-%m-%d").isocalendar()
week_of_year = isodate[1]

例如,计算从周三开始的一周的冲刺数:

def calculate_sprint(sweek):
    calendar.setfirstweekday(calendar.WEDNESDAY)
    isodate=datetime.datetime.strptime(sweek,"%Y-%m-%d").isocalendar()
    return "{year}-{month}".format(year=isodate[0], month=isodate[1])

calculate_sprint('2021-01-01')
>>>'2020-53'

假设您需要将一周与当天的年份组合为字符串。

import datetime
year,week = datetime.date.today().isocalendar()[:2]
week_of_the_year = f"{year}-{week}"
print(week_of_the_year)

你可能会在2021-28年

我相信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]返回周数。尽可能的简单。