[Django]-(Django) how to get month name?

44๐Ÿ‘

โœ…

use the datetime string formatting method, e.g.

>>> today.strftime('%B')
'March'

for more info, and a full list of formatting codes, see the python datetime docs

๐Ÿ‘คsecond

34๐Ÿ‘

For English only, you can use the datetime string formatting method of Python, e.g.

>>> today.strftime('%B')
'March'

You can also use Django methods, which will return the name in the current activated language.

In a Django template you can also use:

{{ a_date|date:'F' }}

In a Django view function:

from django.template.defaultfilters import date
date(a_date, 'F')

You can test the later in the Django shell (python manage.py shell) for e.g. Spanish with:

In [1]: from django.utils.translation import get_language, activate

In [2]: activate('es')

In [3]: get_language()
Out[3]: 'es'

In [4]: import datetime

In [5]: today = datetime.date.today()

In [6]: from django.template.defaultfilters import date

In [7]: date(today, 'F')
Out[7]: u'Septiembre'
๐Ÿ‘คIvan Ogai

10๐Ÿ‘

The Calendar API is another option.

calendar.month_name[3] # would return 'March'
๐Ÿ‘คZain Khan

3๐Ÿ‘

I solved the same by registering a custom template tag to help me apply it on any template page that requires the month name.

templatetags/etras.py

from django import template
import calendar

register = template.Library()

@register.filter
def month_name(value):
    return calendar.month_name[value]

Usage in template:

{% load extras %}
{{ month_figure|month_name }}
๐Ÿ‘คFaith Nassiwa

2๐Ÿ‘

datetime.datetime.strftime(today, '%B') # Outputs 'March'

or

datetime.datetime.strftime(today, '%b') # Outputs 'Mar'

http://docs.python.org/library/datetime.html#strftime-strptime-behavior

๐Ÿ‘คuser391538

2๐Ÿ‘

Month Name to Month Number and vice versa in python

By Using calendar calendar

Creating a reverse dictionary would be a reasonable way to do this:

dict((val,k) for k,v in enumerate(calendar.month_abbr))

๐Ÿ‘คMushahid Khan

1๐Ÿ‘

Pythonโ€™s calendar module will do that for you, see calendar.month_name

month = calendar.month_name[3]
๐Ÿ‘คJoshua Hunter

0๐Ÿ‘

Use strftime:

>>> today = datetime.datetime.now()
>>> today.strftime("%B")
'March'
>>> 
๐Ÿ‘คbgporter

Leave a comment