python 工作日和 strftime ("%U")

标签 python

是否有解决以下问题的方法

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/

相关文章:

python - AttributeError: 'NoneType'对象没有属性 'copy'

python - 导入不带 .py 扩展名的 python 模块

python - Ruby HMAC-SHA 不同于 Python

python - 如何在 bash 脚本中导入 python 文件? (在我的 bash 脚本中使用 python 值)

python - mypy:多种类型的类型注释列表的正确方法

python - 从 Django 过滤器调用返回的列表的默认顺序是什么?

python - 黑盒脚本执行?

python - 如何返回每个分类实例的概率?

python - mod_wsgi 不允许子进程退出

python - 为在子进程中运行的 python 功能测试运行假的 redis