如何在Python中获取周数?

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

datetime.date有一个isocalendar()方法,它返回一个包含日历星期的元组:

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

datetime.date.isocalendar()是一个实例方法,返回一个包含年份,星期编号和星期几的元组,以给定的date实例的相应顺序。

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

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

.isocalendar()返回一个3元组(年,wk num,wk日)。 dt.isocalendar()[0]返回年份, dt.isocalendar()[1]返回周数, dt.isocalendar()[2]返回星期几。 尽可能简单。

您可以直接从date时间获取星期数string。

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

你也可以得到不同的“types”的一年的一周数字更改strftime参数为:

%U – 当年的周数,从第一周的第一个星期天开始。

%V – 当前年度的ISO 8601周数(01至53),其中第一周是当年至less有4天的第一周,周一是本周的第一天。

%W – 当年的周数,从第一个星期一开始,作为第一周的第一天。

我从这里得到了它。 它在Python 2.7.6中为我工作

这是另一个select:

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

打印24

请参阅: http : //docs.python.org/library/datetime.html#strftime-and-strptime-behavior

一般来说,要获得当前周数(从星期天开始):

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

其他人build议的ISO周是好的,但可能不符合您的需求。 它假定每个星期从一个星期一开始,这在一年的开始和结束时会导致一些有趣的exception。

如果您希望使用一个定义,即第1周始终是1月1日到1月7日,而不pipe一周中的哪一天,那么就是这样。

 >>> testdate=datetime.datetime(2010,6,16) >>> print ((testdate - datetime.datetime(testdate.year,1,1)).days // 7) + 1 24 

对于一年中的瞬间星期的整数值,请尝试:

 import datetime datetime.datetime.utcnow().isocalendar()[1] 

如果您只是全面使用isocalendar周数,以下就足够了:

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

这将检索isocalendar为我们的星期编号返回的元组的第二个成员。

但是,如果要使用公历处理的date函数,单独使用isocalendar将不起作用! 以下面的例子:

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

这里的string表示返回2014年第一周的星期一作为我们的date。 当我们使用isocalendar在这里检索周数时,我们希望得到相同的周数,但是我们不这样做。 相反,我们得到一个星期的数字2.为什么?

公历第一周是包含星期一的第一周。 isocalendar中的第一周是包含星期四的第一周。 2014年初的部分星期包含星期四,所以这是第一周的isocalendar,第二周。

如果我们想要得到公历周,我们需要从isocalendar转换到Gregorian。 这是一个简单的function,可以做到这一点。

 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.isocalendar 。

你可以尝试%W指令如下:

 d = datetime.datetime.strptime('2016-06-16','%Y-%m-%d') print(datetime.datetime.strftime(d,'%W')) 

'%W':一年中的星期数(星期一作为一周的第一天)作为十进制数。 在第一个星期一之前的一个新的一年的所有日子被认为是在第0周。(00,01,…,53)

isocalendar()在某些date返回不正确的年份和星期数值:

 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 

我总结了两个步骤的讨论:

  1. 将原始格式转换为datetime对象。
  2. 使用datetime对象或date对象的函数来计算星期数。

暖身

“`python

 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()

但实际上,我们通常需要parsing现有的string。 我们可以使用strptime函数,如datetime.strptime('2017-5-3','%Y-%m-%d') ,其中您必须指定格式。 不同格式代码的细节可以在官方文档中find。

或者,更方便的方法是使用dateparse模块。 例子是dateparser.parse('16 Jun 2010')dateparser.parse('12/2/12') dateparser.parse('2017-5-3') 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. 

“`

决定使用哪种格式非常困难。 更好的方法是获取一个date对象来调用isocalendar() 。 例如,

“`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.isocalendar()来准备每周报告,特别是在“圣诞节 – 新年”购物季节。

 userInput = input ("Please enter project deadline date (dd/mm/yyyy/): ") import datetime currentDate = datetime.datetime.today() testVar = datetime.datetime.strptime(userInput ,"%d/%b/%Y").date() remainDays = testVar - currentDate.date() remainWeeks = (remainDays.days / 7.0) + 1 print ("Please pay attention for deadline of project X in days and weeks are : " ,(remainDays) , "and" ,(remainWeeks) , "Weeks ,\nSo hurryup.............!!!") 

今天的date:

 import datetime as date weeknumber = date.today().isocalendar()[1] 
    Interesting Posts