python日历下拉框_python日历来计算月份倒退
我們正在嘗試在python中創(chuàng)建日歷函數(shù).我們創(chuàng)建了一個小型的內(nèi)容管理系統(tǒng),要求是,網(wǎng)站的右上角會有一個下拉列表,它會給出選項 – 月 – 1個月,2個月,3個月等等. ..,如果用戶選擇8個月,那么它應(yīng)該顯示過去8個月的postscount.問題是我們試圖編寫一個可以進(jìn)行月計算的小代碼,但問題是它沒有考慮當(dāng)年之后的幾個月,它只顯示當(dāng)年的幾個月的postscount.
例如:如果用戶選擇3個月,它將顯示l 3個月(即當(dāng)前月份和前2個月)的計數(shù),但如果用戶選擇超過4個月的選項,則不會考慮上一年的月份,它仍然只顯示今年的月份.
我粘貼下面的代碼: –
def __getSpecifiedMailCount__(request, value):
dbconnector= DBConnector()
CdateList= "select cdate from mail_records"
DateNow= datetime.datetime.today()
DateNow= DateNow.strftime("%Y-%m")
DateYear= datetime.datetime.today()
DateYear= DateYear.strftime("%Y")
DateMonth= datetime.datetime.today()
DateMonth= DateMonth.strftime("%m")
#print DateMonth
def getMonth(value):
valueDic= {"01": "Jan", "02": "Feb", "03": "Mar", "04": "Apr", "05": "May", "06": "Jun", "07": "Jul", "08": "Aug", "09": "Sep", "10": "Oct", "11": "Nov", "12": "Dec"}
return valueDic[value]
def getMonthYearandCount(yearmonth):
MailCount= "select count(*) as mailcount from mail_records where cdate like '%s%s'" % (yearmonth, "%")
MailCountResult= MailCount[0]['mailcount']
return MailCountResult
MailCountList= []
MCOUNT= getMonthYearandCount(DateNow)
MONTH= getMonth(DateMonth)
MailCountDict= {}
MailCountDict['monthyear']= MONTH + ' ' + DateYear
MailCountDict['mailcount']= MCOUNT
var_monthyear= MONTH + ' ' + DateYear
var_mailcount= MCOUNT
MailCountList.append(MailCountDict)
i=1
k= int(value)
hereMONTH= int(DateMonth)
while (i < k):
hereMONTH= int(hereMONTH) - 1
if (hereMONTH < 10):
hereMONTH = '0' + str(hereMONTH)
if (hereMONTH == '00') or (hereMONTH == '0-1'):
break
else:
PMONTH= getMonth(hereMONTH)
hereDateNow= DateYear + '-' + PMONTH
hereDateNowNum= DateYear + '-' + hereMONTH
PMCOUNT= getMonthYearandCount(hereDateNowNum)
MailCountDict= {}
MailCountDict['monthyear']= PMONTH + ' ' + DateYear
MailCountDict['mailcount']= PMCOUNT
var_monthyear= PMONTH + ' ' + DateYear
var_mailcount= PMCOUNT
MailCountList.append(MailCountDict)
i = i + 1
#print MailCountList
MailCountDict= {'monthmailcount': MailCountList}
reportdata = MailCountDict['monthmailcount']
#print reportdata
return render_to_response('test.html', locals())
解決方法:
您可以在datetime模塊中使用timedelta來減去月份.
from datetime import datetime, timedelta
now = datetime.now()
four_months_ago = now - timedelta(days=(4*365)/12)
這將跟蹤在必要時搬回一年……
>>> january_first = datetime(2009, 1,1)
>>> january_first - timedelta(days=(4*365)/12)
datetime.datetime(2008, 9, 2, 0, 0)
標(biāo)簽:python,calendar
來源: https://codeday.me/bug/20190607/1191078.html
總結(jié)
以上是生活随笔為你收集整理的python日历下拉框_python日历来计算月份倒退的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: ubuntu 20 安装vnc_Wind
- 下一篇: python爬虫基本知识_爬虫 (十三)