的困难isocalendar
在于它并没有真正计算每月的日期。因此,您必须翻译回去才能得到它。strptime
可以帮忙:
year, week, dow = datetime.today().isocalendar()
result = [datetime.strptime(str(year) + "-" + str(week-1) + "-" + str(x), "%Y-%W-%w").day for x in range(1,7)]
我们在这里所做的是构建一个striptime
可以理解的字符串,从一周前开始(考虑从 0 到 1 计数)并从一周开始(星期一,即1
)开始,并为每一天构建一个日期时间前进7天。
通过week
在这两个语句之间进行操作(添加或删除几周以达到月休),我们可以看到它有效:
>>> year, week, dow = datetime.today().isocalendar()
>>> result = [datetime.strptime(str(year) + "-" + str(week-1) + "-" + str(x), "%Y-%W-%w").day for x in range(1,7)]
>>> result
[21, 22, 23, 24, 25, 26]
>>> year, week, dow = datetime.today().isocalendar()
>>> week = week + 1
>>> result = [datetime.strptime(str(year) + "-" + str(week-1) + "-" + str(x), "%Y-%W-%w").day for x in range(1,7)]
>>> result
[28, 29, 30, 1, 2, 3]
现在,为了解决评论中提出的两个非常现实的问题,我们必须稍微修改一下:
year, week, dow = datetime.today().isocalendar()
week_start = datetime.strptime(str(year) + "-" + str(week-2) + "-0", "%Y-%W-%w")
result = [(week_start + timedelta(days=x)).day for x in range(0,7)]
这用于timedelta
增加。为了完成这项工作,我们必须跨周间隔进行备份(因此使用-2
代替-1
)。然后,当我们迭代一周时,for 理解增加了一个越来越大的时间增量:
>>> year, week, dow = datetime.today().isocalendar()
>>> week_start = datetime.strptime(str(year) + "-" + str(week-2) + "-0", "%Y-%W-%w")
>>> result = [(week_start + timedelta(days=x)).day for x in range(0,7)]
>>> result
[20, 21, 22, 23, 24, 25, 26]
>>> year, week, dow = datetime.today().isocalendar()
>>> week = week + 1
>>> week_start = datetime.strptime(str(year) + "-" + str(week-2) + "-0", "%Y-%W-%w")
>>> result = [(week_start + timedelta(days=x)).day for x in range(0,7)]
>>> result
[27, 28, 29, 30, 1, 2, 3]