Python获取给定年份的月份开始和结束日期
问题描述:
我想编写一个python函数来获取给定年份的月份开始和结束日期.
I want to write a python function to get months start and end dates for a given year.
示例输入: 2021
预期输出:
[(01-Jan-2021,31-Jan-2021), (01-Feb-2021,28-Feb-2021), (01-Mar-2021,31-Mar-2021), etc..)]
答
您可以使用 pandas
频率别名代表月份的开始和月份的结束.例如:
you can use pandas
date ranges, with appropriate frequency alias for month start and month end. Ex:
import pandas as pd
year, nMonths = "2020", 12
monthStart = pd.date_range(year, periods=nMonths, freq='MS').strftime("%d-%b-%Y")
monthEnd = pd.date_range(year, periods=nMonths, freq='M').strftime("%d-%b-%Y")
l = [(s,e) for s,e in zip(monthStart, monthEnd)]
l
[('01-Jan-2020', '31-Jan-2020'),
('01-Feb-2020', '29-Feb-2020'),
('01-Mar-2020', '31-Mar-2020'),
('01-Apr-2020', '30-Apr-2020'),
('01-May-2020', '31-May-2020'),
('01-Jun-2020', '30-Jun-2020'),
('01-Jul-2020', '31-Jul-2020'),
('01-Aug-2020', '31-Aug-2020'),
('01-Sep-2020', '30-Sep-2020'),
('01-Oct-2020', '31-Oct-2020'),
('01-Nov-2020', '30-Nov-2020'),
('01-Dec-2020', '31-Dec-2020')]