背景
需要2016年至2019年每个月的月初及月末,比如这样:
(‘2016-01-01’, ‘2016-01-31’),
(‘2016-02-01’, ‘2016-02-29’),
(‘2016-03-01’, ‘2016-03-31’),
(‘2016-04-01’, ‘2016-04-30’),
(‘2016-05-01’, ‘2016-05-31’),
(‘2016-06-01’, ‘2016-06-30’),
日历模块calendar可以获取每个月的天数,通过给定月初时间 + 该月天数 , 获得下月月初,然后下月月初减一天既是该月月末。
解决:
引包
import datetime
from datetime import datetime
import calendar
Function
def get_time_range_list(startdate, enddate):
"""
获取时间参数列表
:param startdate: 起始月初时间 --> str
:param enddate: 结束时间 --> str
:return: date_range_list -->list
"""
date_range_list = []
startdate = datetime.datetime.strptime(startdate, '%Y-%m-%d')
enddate = datetime.datetime.strptime(enddate, '%Y-%m-%d')
while 1:
next_month = startdate + datetime.timedelta(days=calendar.monthrange(startdate.year, startdate.month)[1])
month_end = next_month - datetime.timedelta(days=1)
if month_end < enddate:
date_range_list.append((datetime.datetime.strftime(startdate,'%Y-%m-%d'),
datetime.datetime.strftime(month_end,'%Y-%m-%d')))
startdate = next_month
else:
return date_range_list
get_time_range_list("2016-01-01","2019-01-01")
[('2016-01-01', '2016-01-31'),
('2016-02-01', '2016-02-29'),
('2016-03-01', '2016-03-31'),
('2016-04-01', '2016-04-30'),
('2016-05-01', '2016-05-31'),
('2016-06-01', '2016-06-30'),
('2016-07-01', '2016-07-31'),
('2016-08-01', '2016-08-31'),
('2016-09-01', '2016-09-30'),
('2016-10-01', '2016-10-31'),
('2016-11-01', '2016-11-30'),
('2016-12-01', '2016-12-31'),
('2017-01-01', '2017-01-31'),
('2017-02-01', '2017-02-28'),
('2017-03-01', '2017-03-31'),
('2017-04-01', '2017-04-30'),
('2017-05-01', '2017-05-31'),
('2017-06-01', '2017-06-30'),
('2017-07-01', '2017-07-31'),
('2017-08-01', '2017-08-31'),
('2017-09-01', '2017-09-30'),
('2017-10-01', '2017-10-31'),
('2017-11-01', '2017-11-30'),
('2017-12-01', '2017-12-31'),
('2018-01-01', '2018-01-31'),
('2018-02-01', '2018-02-28'),
('2018-03-01', '2018-03-31'),
('2018-04-01', '2018-04-30'),
('2018-05-01', '2018-05-31'),
('2018-06-01', '2018-06-30'),
('2018-07-01', '2018-07-31'),
('2018-08-01', '2018-08-31'),
('2018-09-01', '2018-09-30'),
('2018-10-01', '2018-10-31'),
('2018-11-01', '2018-11-30'),
('2018-12-01', '2018-12-31')]
原文链接:https://blog.csdn.net/weixin_43060843/article/details/102933726