获取python-Django中的上个月内容

时间:2019-12-06 15:00:40

标签: python django

我想在python中生成一个代码,以获取我们所在月份和下个月的前10个月(以获取一些统计信息以及折线图Js中的标签) 例如(我们目前在2019年12月,我希望它显示在2019年2月至2020年1月)

我尝试了旧方法,但是它是固定范围:

        months =[]
        for j in range(12):
            curr_month = calendar.month_name[j]
            my = [curr_month,y]
            months.append(my)
        # print(months)
        lnqs_rfq =[]
        lnqs_local =[]
        allrq = []
        for i in range(12):
            lnqs_rfq.append(Request.objects.filter(req_date__month=(i),req_type='stock').count())
            lnqs_local.append(Request.objects.filter(req_date__month(i),req_type='Local').count())
            allrq.append(Request.objects.filter(req_date__month=(i)).count())

我也尝试过熊猫,但是前几个月我没有得到:

td = datetime.today()
mon = pd.date_range(start=td ,periods = 12, freq='MS').strftime("%b,%Y").tolist()
print(mon)

如果有更好的方法,希望您对我有所帮助。

谢谢

3 个答案:

答案 0 :(得分:0)

from datetime import date

names = ('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec')

def get_date(months): # months - difference in months
    year = date.today().year
    month = date.today().month + months
    if month <= 0:
        year += int(month / 12 - 1)
        month = month % -12 + 12
    elif month > 12:
        year += int((month - 1) / 12)
        month = month % 12
    return '{} {}'.format(names[month - 1], year)

print(get_date(-10), get_date(1), sep=' - ')

输出

2019年2月-2020年1月


如果您想使用库,则可以使用python-dateutil的 relativedelta

from datetime import date
from dateutil.relativedelta import relativedelta

names = ('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec')

def get_date(months):
    rel_date = date.today() + relativedelta(months=months)
    return '{} {}'.format(names[rel_date.month - 1], rel_date.year)

print(get_date(-10), get_date(1), sep=' - ')

输出

2019年2月-2020年1月


并证明他们的行为相同

for i in range(-10000, 10000):
    if get_date(i) != get_date2(i):
        raise Exception('Diversity detected')

print('perfect match')

输出

完美匹配

答案 1 :(得分:0)

您可以使用python-dateutil来实现。

确保使用来安装它

pip install python-dateutil

代码:

from datetime import datetime, timedelta
from dateutil.relativedelta import *
from collections import deque

today = datetime.now()
# Get next month and year using relativedelta
next_month = today + relativedelta(months=+1)
# How many months do you want to go back?
num_months_back = 10

i = 0
deque_months = deque()

while i <= num_months_back:
    curr_date = today + relativedelta(months=-i)
    deque_months.appendleft(curr_date.strftime('%B %Y'))

    if i == num_months_back:
        deque_months.append(next_month.strftime('%B %Y'))

    i = i+1

# Convert deque to list
print(list(deque_months))

输出: enter image description here

答案 2 :(得分:0)

View.py

from rest_framework.views import APIView
from rest_framework.response import Response
from datetime import datetime, timedelta
from dateutil.relativedelta import *
from collections import deque

class ChartData(APIView):

    authentication_classes = []
    permission_classes = []
    def get(self, request, format=None):
        td = datetime.today()
        m =td.month
        y = td.year

        #######LINE Cahrt #######


        today = datetime.now()
        # Get next month and year using relativedelta
        next_month = today + relativedelta(months=+1)
        # How many months do you want to go back?
        num_months_back = 10

        i = 0
        deque_months = deque()

        while i <= num_months_back:
            curr_date = today + relativedelta(months=-i)
            deque_months.appendleft(curr_date.strftime('%B %Y'))

            if i == num_months_back:
                deque_months.append(next_month.strftime('%B %Y'))

            i = i+1

        # Convert deque to list
        print(list(deque_months))


        lnqs_rfq =[]
        lnqs_local =[]
        allrq = []
        for i in range(12):

        lnqs_rfq.append(Request.objects.filter(req_date__month(i),req_type='stock').count())
        lnqs_local.append(Request.objects.filter(req_date__month(i),req_type='Local').count())
        allrq.append(Request.objects.filter(req_date__month=(i)).count())

        total = allrq
        lnrfq_data = lnqs_rfq
        lnlocal_data = lnqs_local

        data ={
            'months':months,
            'lnrfq_data': lnrfq_data,
            'lnlocal_data':lnlocal_data,
            'total':total
        }
        return Response(data)