python获取指定日期之间的月份(亲测有用)
温馨提示:
最后更新时间2020-02-08 13:17:38,若内容或图片失效,请留言反馈!
import datetimefrom dateutil import rruledef get_each_month(start_month, end_month):if str(start_month).count('.') != 1 or str(end_month).count('.') != 1:print("Parameter Error: Pls input a string such as '2019.01'")return []if int(str(start_month).split('.')[1]) > 12 or int(str(end_month).split('.')[1]) > 12:print('Parameter Error: Pls input correct month range such as between 1 to 12')return []if int(str(start_month).split('.')[1]) == 0 or int(str(end_month).split('.')[1]) == 12:print('Parameter Error: Pls input correct month range such as between 1 to 12')return []start = datetime.datetime.strptime(start_month, "%Y.%m")end = datetime.datetime.strptime(end_month, "%Y.%m")month_count = rrule.rrule(rrule.MONTHLY, dtstart=start, until=end).count() # 计算总月份数if end < start:print("Parameter Error: Pls input right date range,start_month can't latter than end_month")return []else:list_month = []year = int(str(start)[:7].split('-')[0]) # 截取起始年份for m in range(month_count): # 利用range函数填充结果列表month = int(str(start)[:7].split('-')[1]) # 截取起始月份,写在for循环里,作为每次迭代的累加基数month = month + mif month > 12:if month % 12 > 0:month = month % 12 # 计算结果大于12,取余数if month == 1:year += 1 # 只需在1月份的时候对年份加1,注意year的初始化在for循环外else:month = 12if len(str(month)) == 1:list_month.append(str(year) + '.0' + str(month))else:list_month.append(str(year) + '.' + str(month))return list_monthmonth_list = get_each_month(str("2019.4"),str(datetime.datetime.now().strftime('%Y.%m')))print(month_list)
文章版权声明:除非注明,否则均为林羽凡原创文章,转载或复制请以超链接形式并注明出处。