Python获取给定年份的月份开始和结束日期 [英] Python get months start and end dates for a given year
本文介绍了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')]
这篇关于Python获取给定年份的月份开始和结束日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文