python如何创建月份列表
时间: 2023-12-03 22:03:15 浏览: 40
可以使用Python中的datetime模块来创建月份列表。下面是一个例子:
```python
from datetime import datetime, timedelta
def get_month_list(start_month, end_month):
start = datetime.strptime(start_month, "%Y-%m")
end = datetime.strptime(end_month, "%Y-%m")
month_list = []
while start <= end:
month_list.append(start.strftime("%Y-%m"))
start += timedelta(days=32)
start = start.replace(day=1)
return month_list
# 示例,获取2019年1月到2019年12月的月份列表
month_list = get_month_list("2019-01", "2019-12")
print(month_list)
```
输出结果为:
```
['2019-01', '2019-02', '2019-03', '2019-04', '2019-05', '2019-06', '2019-07', '2019-08', '2019-09', '2019-10', '2019-11', '2019-12']
```
该函数的参数为起始月份和结束月份,返回一个包含这两个月份之间所有月份的列表。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)