利用python获取当前日期前后N天或N月日期的方法示例
前言
最近因为工作原因,发现一个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)
总结
以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作能带来一定的帮助,如果有疑问大家可以留言交流,谢谢大家对毛票票的支持