Python日期操作
#coding=utf-8
'''
@author: [email protected]
Usage:
Example:
'''
import calendar,datetime,time
import py_compile
def dateformate(formate_str):
formate_str = formate_str.upper()
if formate_str == 'YYYYMMDDHH24MISS':
new_formate = '%Y%m%d%H%M%S'
elif formate_str == 'YYYY-MM-DD HH24:MI:SS':
new_formate = '%Y-%m-%d %H:%M:%S'
elif formate_str == 'YYYYMMDDHH24MI':
new_formate = '%Y%m%d%H%M'
elif formate_str == 'YYYY-MM-DD HH24:MI':
new_formate = '%Y-%m-%d %H:%M'
elif formate_str == 'YYYYMMDDHH24':
new_formate = '%Y%m%d%H'
elif formate_str == 'YYYY-MM-DD HH24':
new_formate = '%Y-%m-%d %H'
elif formate_str == 'YYYYMMDD':
new_formate = '%Y%m%d'
elif formate_str == 'YYYY-MM-DD':
new_formate = '%Y-%m-%d'
elif formate_str == 'YYYYMM':
new_formate = '%Y%m'
elif formate_str == 'YYYY-MM':
new_formate = '%Y-%m'
elif formate_str == 'YYYY':
new_formate = '%Y'
else:
new_formate = None
print "Date format is wrong!Please check it!"
return new_formate
def strtodate(date_str):
if len(date_str) == 8:
date = datetime.datetime.strptime(date_str,'%Y%m%d')
elif len(date_str) == 14:
date = datetime.datetime.strptime(date_str,'%Y%m%d%H%M%S')
else:
date = None
print "Date format is wrong!Please check it like this yyyymmdd or yyyymmddhh24miss."
return date
def strtodate_formate(date_str,date_formate):
date_formate = dateformate(date_formate)
date = datetime.datetime.strptime(date_str,date_formate)
return date
def datetostr(date):
date_str = datetime.datetime.strftime(date,'%Y%m%d%H%M%S')
return date_str
def datetostr_formate(date,date_formate):
date_formate = dateformate(date_formate)
date_str = datetime.datetime.strftime(date,date_formate)
return date_str
def date_inval(date_A,date_B):
inval = (date_B-date_A)
return str(inval)
def add_month(month_str,n):
cur_mon = strtodate(month_str)
targetmonth = n + cur_mon.month
try:
new_mon = cur_mon.replace(year=cur_mon.year+int(targetmonth/12),month=(targetmonth%12))
except:
cur_mon.replace(year=cur_mon.year+int((targetmonth+1)/12),month=((targetmonth+1)%12),day=1)
new_mon = cur_mon + datetime.timedelta(days=-1)
new_month = datetostr(new_mon)
return new_month
def add_day(date_str,n):
new_day = datetostr(strtodate(date_str) + datetime.timedelta(days=n))
return new_day
def add_hour(hour_str,n):
new_hour = datetime.datetime.strftime(datetime.datetime.strptime(hour_str,'%Y%m%d%H%M%S') + datetime.timedelta(hours=n)
,'%Y%m%d%H%M%S')
return new_hour
if __name__=='__main__':