如何在Python中获取周数?

2024-03-29 13:09:20 发布

您现在位置:Python中文网/ 问答频道 /正文


Tags: python
3条回答

我相信date.isocalendar()将是答案。This article解释了ISO 8601日历背后的数学原理。查看Python文档datetime page中的date.isocalendar()部分。

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

.isocalendar()返回一个3元组,其中包含(year,wk num,wk day)。dt.isocalendar()[0]返回年份,dt.isocalendar()[1]返回周数,dt.isocalendar()[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

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

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

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

datetime.date.isocalendar()是一个实例方法,它返回一个元组,该元组按给定日期实例的顺序分别包含year、weeknumber和weekday。

相关问题 更多 >