是否有解决以下问题的方法
from datetime import datetime, timedelta
a = datetime.now() # <== 2016-03-09 11:06:04.824047
print a.strftime("%U")
>>> 10
#go back to previous Sunday
b = a - timedelta(days = 3)
print b.strftime("%U")
>>> 10
print b.weekday()
>>> 6
b.strftime("%U")
不应该是 9
因为它是一周的最后一天吗?
最佳答案
%U
将周视为从星期日开始,而不是从星期一开始。来自documentation :
%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.
您可以使用 %W
格式,它根据 星期一 作为一周的第一天给出一个零填充的周数:
%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.
如果您需要根据 ISO 8601 获取周数,另一种方法是使用 b.isocalendar()[1]
。第 1 周的规则与 ISO 日历计算不同; %W
以一年中的第一个星期一为基础,而 ISO 8601 规定包括 1 月 4 日在内的那一周是第一周。 2016 年两个系统一致,但 2014、2015 或 2019 年情况不同:
>>> d = datetime(2019, 3, 9)
>>> d.strftime('%W')
'09'
>>> d.isocalendar()[1]
10
如果你等到 Python 3.6,你可以使用 %V
格式来包含 ISO 周数,参见 issue 12006 .
关于python 工作日和 strftime ("%U"),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35890293/