欢迎来到代码驿站!

Python代码

当前位置:首页 > 软件编程 > Python代码

python获取指定日期范围内的每一天,每个月,每季度的方法

时间:2020-10-23 16:09:15|栏目:Python代码|点击:

1.获取所有天,返回一个列表:

def getBetweenDay(begin_date):
  date_list = []
  begin_date = datetime.datetime.strptime(begin_date, "%Y-%m-%d")
  end_date = datetime.datetime.strptime(time.strftime('%Y-%m-%d',time.localtime(time.time())), "%Y-%m-%d")
  while begin_date <= end_date:
    date_str = begin_date.strftime("%Y-%m-%d")
    date_list.append(date_str)
    begin_date += datetime.timedelta(days=1)
  return date_list

2.获取所有月,返回一个列表:

def getBetweenMonth(begin_date):
  date_list = []
  begin_date = datetime.datetime.strptime(begin_date, "%Y-%m-%d")
  end_date = datetime.datetime.strptime(time.strftime('%Y-%m-%d', time.localtime(time.time())), "%Y-%m-%d")
  while begin_date <= end_date:
    date_str = begin_date.strftime("%Y%m")
    date_list.append(date_str)
    begin_date = add_months(begin_date,1)
  return date_list
 
def add_months(dt,months):
  month = dt.month - 1 + months
  year = dt.year + month / 12
  month = month % 12 + 1
  day = min(dt.day, calendar.monthrange(year, month)[1])
  return dt.replace(year=year, month=month, day=day)

3.获取所有季度,返回一个列表:

def getBetweenMonth(begin_date):
  date_list = []
  begin_date = datetime.datetime.strptime(begin_date, "%Y-%m-%d")
  end_date = datetime.datetime.strptime(time.strftime('%Y-%m-%d', time.localtime(time.time())), "%Y-%m-%d")
  while begin_date <= end_date:
    date_str = begin_date.strftime("%Y-%m")
    date_list.append(date_str)
    begin_date = add_months(begin_date,1)
  return date_list
 
def add_months(dt,months):
  month = dt.month - 1 + months
  year = dt.year + month / 12
  month = month % 12 + 1
  day = min(dt.day, calendar.monthrange(year, month)[1])
  return dt.replace(year=year, month=month, day=day)
 
def getBetweenQuarter(begin_date):
  quarter_list = []
  month_list = getBetweenMonth(begin_date)
  for value in month_list:
    tempvalue = value.split("-")
    if tempvalue[1] in ['01','02','03']:
      quarter_list.append(tempvalue[0] + "Q1")
    elif tempvalue[1] in ['04','05','06']:
      quarter_list.append(tempvalue[0] + "Q2")
    elif tempvalue[1] in ['07', '08', '09']:
      quarter_list.append(tempvalue[0] + "Q3")
    elif tempvalue[1] in ['10', '11', '12']:
      quarter_list.append(tempvalue[0] + "Q4")
  quarter_set = set(quarter_list)
  quarter_list = list(quarter_set)
  quarter_list.sort()
  return quarter_list

上一篇:python 简易计算器程序,代码就几行

栏    目:Python代码

下一篇:Python爬虫爬验证码实现功能详解

本文标题:python获取指定日期范围内的每一天,每个月,每季度的方法

本文地址:http://www.codeinn.net/misctech/15203.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有