gpt4 book ai didi

python - 查找任何开始日的一周开始时间的更简单方法

转载 作者:行者123 更新时间:2023-11-30 22:42:43 25 4
gpt4 key购买 nike

给定这两个变量,我们需要找到一周的开始(日期时间):

  1. now - 当前日期时间
  2. START_DAY - 我们认为“一周的开始”的星期几(0-6,其中 0 是星期一,6 是星期日)

我们可以使用循环,但这对于一个简单的问题来说似乎步骤太多了:

week_start = datetime(now.year, now.month, now.day)
while week_start.weekday() != START_DAY:
week_start = week_start - timedelta(days=1)

如果 START_DAY 始终为 0(星期一),这真的很容易:

week_start = datetime(now.year, now.month, now.day) - timedelta(days=now.weekday())

或者总是6(周日):

week_start = datetime(now.year, now.month, now.day) - timedelta(days=(0 if now.weekday() == START_DAY else now.weekday() + 1))

计算任意 START_DAY 值的一周开始时间的简单方法是什么?

最佳答案

START_DAYnow 之间的天数为 now.weekday() - START_DAY。但是,如果今天早于 START_DAY(例如,如果今天是星期三,而 START_DATE 是 6 = 星期日),则该数字将为负数,从今天中减去它会得到 future 的日期。

因为您可能不希望这样,所以您需要将差值模 7:

week_start = now.date() - timedelta(days=(now.weekday() - START_DAY) % 7)

示例:

>>> from datetime import datetime, timedelta
>>> now = datetime(2017, 2, 1)
>>> print(now.strftime("%d/%m/%y (%a)"))
01/02/17 (Wed)
>>> for START_DAY in range(7):
... start_week = now.date() - timedelta(days=(now.weekday() - START_DAY) % 7)
... print(start_week.strftime("%d/%m/%y (%a)"))
...
30/01/17 (Mon)
31/01/17 (Tue)
01/02/17 (Wed)
26/01/17 (Thu)
27/01/17 (Fri)
28/01/17 (Sat)
29/01/17 (Sun)

关于python - 查找任何开始日的一周开始时间的更简单方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42036846/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com