本文翻译自:How to get week number in Python?
如何使用Python找出6月16日(wk24)当前年份的周数?
#1楼
参考:https://stackoom.com/question/aUzZ/如何在Python中获取周数
#2楼
isocalendar() returns incorrect year and weeknumber values for some dates: isocalendar()为某些日期返回不正确的年份和周数值:
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
Compare with Mark Ransom's approach: 与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
#3楼
datetime.date has a isocalendar() method, which returns a tuple containing the calendar week: datetime.date有一个isocalendar()方法,它返回一个包含日历周的元组:
>>> import datetime
>>> datetime.date(2010, 6, 16).isocalendar()[1]
24
datetime.date.isocalendar() is an instance-method returning a tuple containing year, weeknumber and weekday in respective order for the given date instance. datetime.date.isocalendar()是一个实例方法,以给定日期实例的相应顺序返回包含年,周数和工作日的元组。
#4楼
查看datetime.datetime.isocalendar 。
#5楼
I believe date.isocalendar() is going to be the answer. 我相信date.isocalendar()将成为答案。 This article explains the math behind ISO 8601 Calendar. 本文解释了ISO 8601日历背后的数学。 Check out the date.isocalendar() portion of the datetime page of the Python documentation. 查看Python文档的datetime页面的date.isocalendar()部分。
>>> dt = datetime.date(2010, 6, 16)
>>> wk = dt.isocalendar()[1]
24
.isocalendar() return a 3-tuple with (year, wk num, wk day). .isocalendar()返回一个3元组(年,周数,周日)。 dt.isocalendar()[0] returns the year, dt.isocalendar()[1] returns the week number, dt.isocalendar()[2] returns the week day. dt.isocalendar()[0]返回年份, dt.isocalendar()[1]返回周数, dt.isocalendar()[2]返回工作日。 Simple as can be. 很简单就可以了。
#6楼
Here's another option: 这是另一种选择:
import time
from time import gmtime, strftime
d = time.strptime("16 Jun 2010", "%d %b %Y")
print(strftime("%U", d))
which prints 24 . 打印24 。
See: http://docs.python.org/library/datetime.html#strftime-and-strptime-behavior 请参阅: http : //docs.python.org/library/datetime.html#strftime-and-strptime-behavior
本文探讨了在Python中计算特定日期所在周数的多种方法,包括使用datetime模块的isocalendar()函数,以及通过日期差计算周数的替代方案。文章对比了不同方法的计算结果,解释了ISO8601日历标准,并提供了代码示例。

6450

被折叠的 条评论
为什么被折叠?



