在这之后,我试图得到本月最后一个星期四的日期。但我的代码不会失控。
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
的文档
注意,如果计算的日期已经Monday
,例如,使用(0, 1)
或(0, -1)
不会更改日期。
如果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