Python calendar to calculate a month ago

we are trying to create a calendar function in python. we have created a small content management system, the requirement is that in the upper right corner of the website there will be a drop-down list that will give options - Months - 1 month, 2 months, 3 months, etc ... if the user selects 8 months, then it should show the column for the last 8 months. the problem is that we tried to write a small code that will perform the calculations of the month, but the error is that it does not take into account months outside the current year, it shows the number of columns only during the months of the current year.

for example: if the user selects 3 months, he will show the bill for 1 3 months, i.e. the current month and the previous 2 months, but if the user selects the option for more than 4 months, he does not take into account the months from the previous year, he still shows only the month of the current year.

I am inserting the code below: -


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()) 

+4
source share
3 answers

You can use timedelta in the datetime module to subtract months.

 from datetime import datetime, timedelta now = datetime.now() four_months_ago = now - timedelta(days=(4*365)/12) 

This will track the movement back in the year when necessary ...

 >>> january_first = datetime(2009, 1,1) >>> january_first - timedelta(days=(4*365)/12) datetime.datetime(2008, 9, 2, 0, 0) 
-2
source

The relativedelta function in the python-dateutil package does the trick:

 from dateutil.relativedelta import * import datetime five_months_ago = datetime.datetime.now() - relativedelta(months=5) 
+6
source

This is an uncomfortable problem because months have different lengths. What is July 31 minus one month? I had a similar requirement, but I made the simplifying assumption that I always wanted the first day of the month, n months ago. In case it will be useful for your requirements, here it is:

 from datetime import date def add_months(start_date, months): return date( start_date.year + (start_date.month - 1 + months) / 12, (start_date.month - 1 + months) % 12 + 1, 1) 
+1
source

Source: https://habr.com/ru/post/1306997/


All Articles