Django计算两个日期间的月份和天数

计算月份

def get_month_range(start_day,end_day):
  months = (end_day.year - start_day.year)*12 + end_day.month - start_day.month
  month_range = ['%s-%s'%(start_day.year + mon//12,mon%12+1) 
                    for mon in range(start_day.month-1,start_day.month + months)]
  return month_range
>get_month_range(datetime.date(2016, 1, 31),datetime.date(2017,3,26))
 ['2016-1',
 '2016-2',
 '2016-3',
 '2016-4',
 '2016-5',
 '2016-6',
 '2016-7',
 '2016-8',
 '2016-9',
 '2016-10',
 '2016-11',
 '2016-12',
 '2017-1',
 '2017-2',
 '2017-3']

 计算天数

# 根据开始日期、结束日期返回这段时间里所有天的集合
def getDatesByTimes(sDateStr, eDateStr):
    list = []
    datestart = datetime.datetime.strptime(sDateStr, '%Y-%m-%d')
    dateend = datetime.datetime.strptime(eDateStr, '%Y-%m-%d')
    list.append(datestart.strftime('%Y-%m-%d'))
    while datestart < dateend:
        datestart += datetime.timedelta(days=1)
        list.append(datestart.strftime('%Y-%m-%d'))
    return list
##测试
print(getDatesByTimes('2019-2-26','2019-3-25'))
##测试结果
['2019-02-26', '2019-02-27', '2019-02-28', '2019-03-01', '2019-03-02', '2019-03-03', '2019-03-04',
 '2019-03-05', '2019-03-06', '2019-03-07', '2019-03-08', '2019-03-09', '2019-03-10', '2019-03-11', 
'2019-03-12', '2019-03-13', '2019-03-14', '2019-03-15', '2019-03-16', '2019-03-17', '2019-03-18', 
'2019-03-19', '2019-03-20', '2019-03-21', '2019-03-22', '2019-03-23', '2019-03-24', '2019-03-25']

 日期计算

##多加一天
print (datetime.datetime.now()+datetime.timedelta(days=1)).strftime("%Y-%m-%d %H:%M:%S")

##多加一小时
print (datetime.datetime.now()+datetime.timedelta(hours=1)).strftime("%Y-%m-%d %H:%M:%S")
##多加一分钟
print (datetime.datetime.now()+datetime.timedelta(minutes=1)).strftime("%Y-%m-%d %H:%M:%S")

  

  

原文地址:https://www.cnblogs.com/sunzhiqi/p/14149432.html