gpt4 book ai didi

python - 使用python获取当月的最后一个星期四

转载 作者:太空狗 更新时间:2023-10-30 02:28:26 26 4
gpt4 key购买 nike

关注此answer我试图获取当月最后一个星期四的日期。但是我的代码没有跳出循环。

from datetime import datetime
from dateutil.relativedelta import relativedelta, TH

todayte = datetime.today()
cmon = todayte.month

nthu = todayte
while nthu.month == cmon:
nthu += relativedelta(weekday=TH(1))
#print nthu.strftime('%d%b%Y').upper()

最佳答案

查看 relativedelta 的文档

Notice that if the calculated date is already Monday, for example, using (0, 1) or (0, -1) won’t change the day.

如果 nthu 已经是星期四,那么添加 TH(1)TH(-1) 不会有任何效果,但会导致同一日期,这就是您的循环无限运行的原因。

我假设一个月最多 5 周,并按以下方式进行:

todayte = datetime.today()
cmon = todayte.month

for i in range(1, 6):
t = todayte + relativedelta(weekday=TH(i))
if t.month != cmon:
# since t is exceeded we need last one which we can get by subtracting -2 since it is already a Thursday.
t = t + relativedelta(weekday=TH(-2))
break

关于python - 使用python获取当月的最后一个星期四,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36975886/

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