放两个小轮子吧,欢迎测试bug,然后告诉我:
1、返回指定日期所在的一周
2,计算一个日期的月份和天数加减
# -*- coding: utf-8 -*-
"""
Created on Tue May 17 17:11:28 2016
@author: pcloth
关于日期的计算轮子
"""
import datetime,time,calendar
# 提交一个日期参数date(可以是字符串日期,也可以是datetime.date日期)
# 返回该日期所在的一周的日期list,从星期一到星期日
#
# 如:thisweek('2016-07-18')
# Out:
#[datetime.date(2016, 7, 18),
# datetime.date(2016, 7, 19),
# datetime.date(2016, 7, 20),
# datetime.date(2016, 7, 21),
# datetime.date(2016, 7, 22),
# datetime.date(2016, 7, 23),
# datetime.date(2016, 7, 24)]
def thisweek(date):
if type(date)==str:
try:
date_input = datetime.date.fromtimestamp(time.mktime(time.strptime(date,"%Y-%m-%d")))
except:
raise '参数错误:str格式的日期不合法,期待值格式:‘2016-01-01’'
elif type(date)==datetime.date:
date_input = date
else:
raise '参数错误:日期必须是datetime.date格式或者是str格式的合法日期比如‘2016-01-01’'
n = datetime.datetime.weekday(date_input)
weeklist = []
for i in range(7):
this_day=date_input + datetime.timedelta(0-n+i)
weeklist.append(this_day)
return weeklist
# 对一个datetime.date日期(或者str格式的日期)数据进行加减:
## add_months 是叠加的月数
# add_days 是叠加的天数
#
# 例如:date_add(datetime.date(2016,7,18),add_days=1)
# Out[65]: datetime.date(2016, 7, 19)
#
# date_add(datetime.date(2016,7,18),add_months=2,add_days=1)
# Out[66]: datetime.date(2016, 9, 19)
#
# 当然,参数也可以是负数:
# date_add('2016-01-01',add_months=-2,add_days=-1)
# Out[79]: datetime.date(2015, 10, 31)
#
#
def date_add(dt,add_months=0,add_days=0):
if type(dt)==str:
try:
dt = datetime.date.fromtimestamp(time.mktime(time.strptime(dt,"%Y-%m-%d")))
except:
raise '参数错误:日期必须是datetime.date格式或者是str格式的合法日期比如‘2016-01-01’'
month = dt.month + add_months
year = dt.year
if month>12:
year += int(month/12)
month = max(month%12,1)
elif month<0:
if abs(month)/12 > 0 and abs(month)/12 < 1:
year -= 1
month += 12
else:
year -= (int(abs(month)/12)+1)
month += (int(abs(month)/12)+1)*12
if month==0:
year -= 1
month = 12 - month
day = min(dt.day,calendar.monthrange(year,month)[1])
dt = dt.replace(year=year, month=month, day=day)
if add_days!=0:
dt = dt + datetime.timedelta(add_days)
return dt