gpt4 book ai didi

Python:知道给定日期的下个月的第二个星期三

转载 作者:太空狗 更新时间:2023-10-30 01:55:43 24 4
gpt4 key购买 nike

我想知道这个:

例如我有这个日期:

2011-08-10 wednesday

我想知道下个月的第二个星期三:答案应该是 2011-09-14 星期三

最佳答案

在评论中解释说 OP 正在寻找映射的函数

  1. 2011-08-25(第四个星期四)至 2011-09-22(第四个星期四下个月)和
  2. 2011-08-30(第五个星期二)到 2011-09-27(第四个星期二,因为九月没有第五个星期二。)

使用 dateutil :

import datetime
import dateutil.relativedelta as relativedelta

def next_month(date):
weekday=relativedelta.weekday(date.isoweekday()-1)
weeknum=(date.day-1)//7+1
weeknum=weeknum if weeknum<=4 else 4
next_date=date+relativedelta.relativedelta(
months=1,day=1,weekday=weekday(weeknum))
return next_date

start=datetime.date(2011,8,1)
for i in range(31):
date=start+datetime.timedelta(days=i)
next_date=next_month(date)
print('{d} --> {n}'.format(d=date,n=next_date))

产量

2011-08-01 --> 2011-09-05
2011-08-02 --> 2011-09-06
2011-08-03 --> 2011-09-07
2011-08-04 --> 2011-09-01
2011-08-05 --> 2011-09-02
2011-08-06 --> 2011-09-03
2011-08-07 --> 2011-09-04
2011-08-08 --> 2011-09-12
2011-08-09 --> 2011-09-13
2011-08-10 --> 2011-09-14
2011-08-11 --> 2011-09-08
2011-08-12 --> 2011-09-09
2011-08-13 --> 2011-09-10
2011-08-14 --> 2011-09-11
2011-08-15 --> 2011-09-19
2011-08-16 --> 2011-09-20
2011-08-17 --> 2011-09-21
2011-08-18 --> 2011-09-15
2011-08-19 --> 2011-09-16
2011-08-20 --> 2011-09-17
2011-08-21 --> 2011-09-18
2011-08-22 --> 2011-09-26
2011-08-23 --> 2011-09-27
2011-08-24 --> 2011-09-28
2011-08-25 --> 2011-09-22 # Oddly non-monotonic, but correct according to specifications
2011-08-26 --> 2011-09-23
2011-08-27 --> 2011-09-24
2011-08-28 --> 2011-09-25
2011-08-29 --> 2011-09-26 # 5th Monday maps to 4th Monday since there is no 5th Monday in September
2011-08-30 --> 2011-09-27
2011-08-31 --> 2011-09-28

关于Python:知道给定日期的下个月的第二个星期三,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7025028/

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