from datetime import datey1, m1 = stlmt_date[0].year, stlmt_date[0].monthy2, m2 = stlmt_date[1].year, stlmt_date[1].monthif y1 < y2:raise Exception('起止年月有问题,{} to {}'.format(stlmt_date[0], stlmt_date[1]))import calendarfrom datetime import datetime, timedeltadef days_in_month(dt):'''获取某个月有多少天'''return calendar.monthrange(dt.year, dt.month)[1]def monthly_range(dt_start, dt_end):forward = dt_end >= dt_startfinish = Falsedt = dt_startwhile not finish: yield dtif forward:days = days_in_month(dt)dt = dt + timedelta(days=days) finish = dt > dt_endelse:_tmp_dt = dt.replace(day=1) - timedelta(days=1)dt = (_tmp_dt.replace(day=dt.day))finish = dt < dt_end
如果觉得《利用python计算每个月有多少天和在两个日期中按月遍历》对你有帮助,请点赞、收藏,并留下你的观点哦!