Python 获得指定日期范围内的日期和月份

#获得指定日期之间的日期数,时间格式为 %Y-%m-%d
from datetime import datetime,timedelta
def getDayIter(start_date, end_date):
    #时间格式为 %Y-%m-%d
    out_day_arr = []
    dt_date = datetime.strptime(start_date, '%Y-%m-%d')
    dt_str = start_date
    while dt_str <= end_date:
        out_day_arr.append(dt_str)
        dt_date = dt_date + timedelta(days=1)
        dt_str = dt_date.strftime('%Y-%m-%d')
    return out_day_arr



#获得指定月份之间的月份数,时间格式为 %Y-%m
from datetime import datetime,timedelta
import calendar
def getMonthIter(start_month, end_month):
    #时间格式为 %Y-%m
    out_month_arr = []
    dt_date = datetime.strptime(start_month, '%Y-%m')
    dt_str = start_month
    while dt_str <= end_month:
        out_month_arr.append(dt_str)
        dt_date = dt_date + timedelta(days=calendar.monthrange(dt_date.year, dt_date.month)[1])
        dt_str = dt_date.strftime('%Y-%m')
    return out_month_arr

  进行测试

print(getMonthIter('2021-01', '2022-03'))

#输出
#['2021-01', '2021-02', '2021-03', '2021-04', '2021-05', '2021-06', '2021-07', #'2021-08', '2021-09', '2021-10', '2021-11', '2021-12', '2022-01', '2022-02', #'2022-03']

print(getDayIter('2021-12-23', '2022-01-12'))
#输出
#['2021-12-23', '2021-12-24', '2021-12-25', '2021-12-26', '2021-12-27', '2021-#12-28', '2021-12-29', '2021-12-30', '2021-12-31', '2022-01-01', '2022-01-02', #'2022-01-03', '2022-01-04', '2022-01-05', '2022-01-06', '2022-01-07', '2022-#01-08', '2022-01-09', '2022-01-10', '2022-01-11', '2022-01-12']

  

posted @ 2022-04-12 17:50  Blues.huang  阅读(1019)  评论(0编辑  收藏  举报