########2018-08-20
month相加减, 使用datetime.timedelta(days),其中days可以自己先计算出来,代码如下:
def deltaTime(start = None, format = None, months = 0,days = 0, hours = 0):
#days = None, seconds = None, microseconds = None, milliseconds = None, minutes = None, hours = None, weeks = None
if start and format:
start_date = datetime.strptime(start, format)
else:
start_date = datetime.now()
d2 = start_date
if months:
d2 = monthdelta(start_date,months)
elif days or hours:
d2 = start_date + timedelta(days = days,hours = 0)
return d2.strftime(format)
def monthdelta(start_date,months):
for i in range(abs(months)):
if months > 0:
days = getMaxDay(start_date.year,start_date.month)
elif months < 0 :
days = -getMaxDay(start_date.year,start_date.month)
start_date = start_date + timedelta(days = days)
return start_date
def getMaxDay(year,month):
maxDay = [31,year%100 and (year%4 and 28 or 29) or (year%400 and 28 or 29),31,30,31,30,31,31,30,31,30,31]
return maxDay[month-1]
#########2018-03-28
时间的计算python的datetime提供了个timedelta , 函数原型如下, 但其不能计算年 月
datetime.timedelta(days=0, seconds=0, microseconds=0, milliseconds=0, minutes=0, hours=0, weeks=0)
那如何简单有效的计算年 月的呢?python的time的localtime等会返回time.struct_time结果,其格式如下,这个类型只能读, 不能直接修改.
time.struct_time(tm_year=2018, tm_mon=3, tm_mday=28, tm_hour=15, tm_min=22, tm_sec=19, tm_wday=2, tm_yday=87, tm_isdst=0)
所以, 就可以根据time.localtime的返回结果来计算年 月 日 时 分 秒了:
def deltaTime(self,year = 0,month = 0,day = 0,hour = 0,minute = 0,second = 0):
t = time.localtime()
return "%04d%02d%02d%02d%02d%02d"%(t.tm_year + year,t.tm_mon + month,t.tm_mday + day,t.tm_hour + hour,t.tm_min + minute,t.tm_sec + second)
使用:
deltaTime(year = -10) #'20080328153606'
deltaTime(year = 10)#'20280328153601'
可以根据这个方法举一反三, 两个给定时间,时间戳等的计算,返回不同的格式等.