python 日历向后计算月份

发布于 2024-08-29 03:33:01 字数 2517 浏览 3 评论 0原文

我们正在尝试用 python 创建一个日历函数。我们创建了一个小型内容管理系统,要求是,网站右上角会有一个下拉列表,其中会提供选项 - 月份 - 1 个月、2 个月、3 个月等。 ..,如果用户选择 8 个月,那么它应该显示过去 8 个月的帖子计数。问题是我们尝试编写一个小代码来进行月份计算,但错误是它不考虑当前年份之外的月份,它仅显示当前年份月份的帖子计数。

例如:如果用户选择3个月,它将显示l 3个月的计数,即当前月份和前2个月,但如果用户选择超过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())

we are trying to create a calendar function in python. we have created a small content management system, the requirement is, there will be a drop down list on the top right hand corner of the website, which will give the options - Months - 1 month, 2 months, 3 months and so on..., if the user selects 8 months then it should show the postscount for the last 8 months. the issue is we tried to write a small code which would do the month calculations, but the bug is that it does not consider the months beyond the current year, it shows the postscount only for months of the current year.

for example: if the user selects 3 months, it will show the count for the l 3 months i.e present month and the previous 2 months, but if the user selects option more than 4 months, it does not consider the months from previous year, it still shows the month of the present year only.

I am pasting 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())

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

瞎闹 2024-09-05 03:33:01

python-dateutil 包中的relativedelta 函数可以解决这个问题:

from dateutil.relativedelta import *
import datetime

five_months_ago = datetime.datetime.now() - relativedelta(months=5)

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)
失与倦" 2024-09-05 03:33:01

这是一个尴尬的问题,因为月份的长度不同。 7 月 31 日减一个月是多少?我有类似的要求,但我做了一个简化的假设,我总是想要 n 个月前的一个月的第一天。如果它对您的要求有帮助,这里是:

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)

This is an awkward 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's helpful 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)
挽容 2024-09-05 03:33:01

您可以使用 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)

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 keep track of moving back a year when necessary...

>>> january_first = datetime(2009, 1,1)
>>> january_first - timedelta(days=(4*365)/12)
datetime.datetime(2008, 9, 2, 0, 0)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文