python 日期操作类代码
完整代码
#-*-coding:utf-8-*- '''获取当前日期前后N天或N月的日期''' fromtimeimportstrftime,localtime fromdatetimeimporttimedelta,date importcalendar year=strftime("%Y",localtime()) mon=strftime("%m",localtime()) day=strftime("%d",localtime()) hour=strftime("%H",localtime()) min=strftime("%M",localtime()) sec=strftime("%S",localtime()) deftoday(): ''''' gettoday,dateformat="YYYY-MM-DD" ''''' returndate.today() deftodaystr(): ''' getdatestring,dateformat="YYYYMMDD" ''' returnyear+mon+day defdatetime(): ''''' getdatetime,format="YYYY-MM-DDHH:MM:SS" ''' returnstrftime("%Y-%m-%d%H:%M:%S",localtime()) defdatetimestr(): ''''' getdatetimestring dateformat="YYYYMMDDHHMMSS" ''' returnyear+mon+day+hour+min+sec defget_day_of_day(n=0): ''''' ifn>=0,dateislargerthantoday ifn<0,dateislessthantoday dateformat="YYYY-MM-DD" ''' if(n<0): n=abs(n) returndate.today()-timedelta(days=n) else: returndate.today()+timedelta(days=n) defget_days_of_month(year,mon): ''''' getdaysofmonth ''' returncalendar.monthrange(year,mon)[1] defget_firstday_of_month(year,mon): ''''' getthefirstdayofmonth dateformat="YYYY-MM-DD" ''' days="01" if(int(mon)<10): mon="0"+str(int(mon)) arr=(year,mon,days) return"-".join("%s"%iforiinarr) defget_lastday_of_month(year,mon): ''''' getthelastdayofmonth dateformat="YYYY-MM-DD" ''' days=calendar.monthrange(year,mon)[1] mon=addzero(mon) arr=(year,mon,days) return"-".join("%s"%iforiinarr) defget_firstday_month(n=0): ''''' getthefirstdayofmonthfromtoday nishowmanymonths ''' (y,m,d)=getyearandmonth(n) d="01" arr=(y,m,d) return"-".join("%s"%iforiinarr) defget_lastday_month(n=0): ''''' getthelastdayofmonthfromtoday nishowmanymonths ''' return"-".join("%s"%iforiingetyearandmonth(n)) defgetyearandmonth(n=0): ''''' gettheyear,month,daysfromtoday befororafternmonths ''' thisyear=int(year) thismon=int(mon) totalmon=thismon+n if(n>=0): if(totalmon<=12): days=str(get_days_of_month(thisyear,totalmon)) totalmon=addzero(totalmon) return(year,totalmon,days) else: i=totalmon/12 j=totalmon%12 if(j==0): i-=1 j=12 thisyear+=i days=str(get_days_of_month(thisyear,j)) j=addzero(j) return(str(thisyear),str(j),days) else: if((totalmon>0)and(totalmon<12)): days=str(get_days_of_month(thisyear,totalmon)) totalmon=addzero(totalmon) return(year,totalmon,days) else: i=totalmon/12 j=totalmon%12 if(j==0): i-=1 j=12 thisyear+=i days=str(get_days_of_month(thisyear,j)) j=addzero(j) return(str(thisyear),str(j),days) defaddzero(n): ''''' add0before0-9 return01-09 ''' nabs=abs(int(n)) if(nabs<10): return"0"+str(nabs) else: returnnabs defget_today_month(n=0): ''''' 获取当前日期前后N月的日期 ifn>0,获取当前日期前N月的日期 ifn<0,获取当前日期后N月的日期 dateformat="YYYY-MM-DD" ''' (y,m,d)=getyearandmonth(n) arr=(y,m,d) if(int(day)这篇关于python日期操作类的文章就介绍到这,里面涉及了python日期操作的一些基础知识。