遍历日历月份的开始/结束日期可以使用datetime模块来实现。下面是一个示例代码:
import datetime
def get_month_range(start_date, end_date):
start_month = start_date.replace(day=1)
end_month = end_date.replace(day=1)
month_range = []
while start_month <= end_month:
month_range.append((start_month, start_month + datetime.timedelta(days=31)))
next_month = start_month.month + 1 if start_month.month != 12 else 1
next_year = start_month.year + 1 if next_month == 1 else start_month.year
start_month = start_month.replace(month=next_month, year=next_year)
return month_range
# 示例用法
start_date = datetime.datetime(2021, 1, 15)
end_date = datetime.datetime(2021, 5, 20)
months = get_month_range(start_date, end_date)
for month in months:
print("开始日期:", month[0])
print("结束日期:", month[1])
print()
这个示例代码中,我们定义了一个get_month_range
函数,它接受一个起始日期和一个结束日期,并返回一个包含所有月份开始日期和结束日期的列表。在循环中,我们通过replace
方法将日期的日部分替换为1,得到月份开始日期。然后,我们通过timedelta
方法加上31天来得到月份结束日期(这里假设一个月最多有31天)。接着,我们更新start_month
为下一个月的开始日期,并继续循环直到start_month
超过end_month
。
示例用法中,我们设定起始日期为2021年1月15日,结束日期为2021年5月20日,然后遍历打印每个月份的开始日期和结束日期。你可以根据自己的需求来修改起始日期和结束日期。
下一篇:遍历日期返回 null