Python获取给定时间段内的每月第一天以及最后一天

背景
需要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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值