您实际上只是在检查一年是否是闰,然后确定二月的长度。这可能是一种简单的方法:
import calendar
def MonthsStartAndEnd(year):
# create dictionary of normal month lengths
months = {
'Jan': '31',
'Feb': '28',
'Mar': '31',
'Apr': '30',
'May': '31',
'Jun': '30',
'Jul': '31',
'Aug': '31',
'Sep': '30',
'Oct': '31',
'Nov': '30',
'Dec': '31'
}
# check if the year is leap and if so update Feb to 29 days
if calendar.isleap(year):
months['Feb'] = '29'
# return the formatted list of values
return [f"01-{key}-{year},{value}-{key}-{year}" for key, value in months.items()]
print(MonthsStartAndEnd(2000))
print(MonthsStartAndEnd(2001))
#['01-Jan-2000,31-Jan-2000', '01-Feb-2000,29-Feb-2000', '01-Mar-2000,31-Mar-2000', '01-Apr-2000,31-Apr-2000', '01-May-2000,31-May-2000', '01-Jun-2000,31-Jun-2000', '01-Jul-2000,31-Jul-2000', '01-Aug-2000,31-Aug-2000', '01-Sep-2000,31-Sep-2000', '01-Oct-2000,31-Oct-2000', '01-Nov-2000,31-Nov-2000', '01-Dec-2000,31-Dec-2000']
['01-Jan-2001,31-Jan-2001', '01-Feb-2001,28-Feb-2001', '01-Mar-2001,31-Mar-2001', '01-Apr-2001,31-Apr-2001', '01-May-2001,31-May-2001', '01-Jun-2001,31-Jun-2001', '01-Jul-2001,31-Jul-2001', '01-Aug-2001,31-Aug-2001', '01-Sep-2001,31-Sep-2001', '01-Oct-2001,31-Oct-2001', '01-Nov-2001,31-Nov-2001', '01-Dec-2001,31-Dec-2001']