1

Forgive me If i'm asking a very stupid questions.

I'm trying to get name of the past months instead of numbers my django framework:

Example: For instance, if I have 12, I want to return december or dec

Right now, I had this external python scripts that sort the day, weeks, month and years.

Here the codes for external scripts Name;basicfun: (only on the months)

#basicfun codes (external python scripts)  

 def selectDates(query):

    if query == 'Previous-Months':
    dataset = datetime.now().month - 1
    dataset.strftime("%b")

 return dataset 

It will return to my django view to use as a filter for Queryset

Here the Frame works codes on view:

#Django view 
       def ph(request):
            query = request.GET.get('dateRange')
            fill = selectDates(query)
            data = tank_system.objects.all().filter(datetime__contains=fill)
            return render(request, 'FrounterWeb/extends/ph.html', {'tank': data})

Solution I had try

This link: Get month name from number

1.

   dataset = datetime.now().month - 1
   dataset.strftime("%b") 

error:

Exception Type:AttributeError
Exception Value:'int' object has no attribute 'strftime'
I'm stupid
  • 67
  • 10

3 Answers3

3

Your error is because datetime.now().month is an integer. strftime is a method on the datetime object.

You can get the current month by doing:

month = datetime.now().strftime("%b")

To get previous month names, easy but sort of "hacky" way to do this would be to just create a dictionary of the month strings you want with the month number as keys:

from datetime import datetime

def limit_month_number(start_month, months_ago):
    """
    This function will return a value from 1-12 inclusive.
    >>> limit_month_number(1,3) -> 10
    >>> limit_month_number(12,14) -> 10
    """
    month_number = start_month - (months_ago % 12)
    if month_number < 1:
        month_number = 12 + month_number 
    return month_number

def get_prev_month(months_ago):
    months = {1: 'Jan', 2: 'Feb', 10: 'Oct', 11: 'Nov', 12: 'Dec'}

    this_month = datetime.now().month

    month_number = limit_month_number(this_month, months_ago)

    prev_month = months[month_number]
    return prev_month

print(get_prev_month(2)) # 'Nov', two months ago from now

Also, I must point out that you can do this using datetime. Check out this other post: python date of the previous month

Kevin Welch
  • 1,488
  • 1
  • 9
  • 18
  • thank you Kevin it work on the current month, as the previous month as you said is really hacky – I'm stupid Jan 04 '19 at 07:43
  • The benefit of using your own dictionary is that you have the choice of using the abbreviation or the full name of the month. – Kevin Welch Jan 04 '19 at 07:50
  • I didn't get last month but this months instead, I wonder is becuase the turn didn't work? – I'm stupid Jan 04 '19 at 07:57
  • I made an edit to the code. Try that out. I will let you fill in the other 7 months yourself. – Kevin Welch Jan 04 '19 at 08:07
  • 1
    @KevinWelch You can reduce the 'hackiness' by using the standard library's [calendar](https://docs.python.org/3/library/calendar.html) module to provide the month names - see the `month_name` and `month_abbr` attributes. – snakecharmerb Jan 05 '19 at 11:13
2

Use relativedelta.

from dateutil.relativedelta import relativedelta

today = dt.date.today()  # 2019-01-03
>>> (today - relativedelta(months=1)).strftime('%B')  # `%b' for abbreviated month
'December'

For the last three months, you could use a list comprehension:

>>> [(dt.date.today() - relativedelta(months=x)).strftime('%B') for x in range(3, 0, -1)]
['October', 'November', 'December']
Alexander
  • 105,104
  • 32
  • 201
  • 196
  • Do you need to install relativedlta? becuase #from detutil.relativedelta import relativedelta# Django do not reconsider – I'm stupid Jan 04 '19 at 07:38
2

Try this

previous_month = (datetime.date.today().replace(day=1) - datetime.timedelta(days=1)).strftime('%B')
shafik
  • 6,098
  • 5
  • 32
  • 50