Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

(Django) how to get month name?

Tags:

I have a query like below:

today = datetime.datetime.now() month = today.month print month 

and it outputs:

3 

I want to display the month name like "March". What should I do?

like image 776
Eren Süleymanoğlu Avatar asked Mar 08 '12 16:03

Eren Süleymanoğlu


2 Answers

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

like image 85
second Avatar answered Sep 19 '22 11:09

second


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' 
like image 24
Ivan Ogai Avatar answered Sep 21 '22 11:09

Ivan Ogai