2012-03-08 14 views
13

私は以下のようなクエリている:私は、 "マーチ" のような月の名前を表示したい(Django)月名の取得方法は?

3 

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

をし、それが出力します。私は何をすべきか?

+0

なし私のために良いではない... – lvella

答えて

31

は、日付/時刻文字列フォーマット方法を使用します。

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

詳細情報、および書式コードの完全なリストについては、参照the python datetime docs

+0

はあなたに男を感謝:) –

0

使用のstrftime:

>>> today = datetime.datetime.now() 
>>> today.strftime("%B") 
'March' 
>>> 
8

Calendar APIは別のオプションです。

calendar.month_name[3] # would return 'March' 
1

あなたのためにそれを行うだろうPythonのカレンダーモジュールは、だろうreverse dictionaryを作成するカレンダーにcalendar

を使用した

pythonMonth Numberおよびその逆にcalendar.month_name

month = calendar.month_name[3] 
2

Month Nameを見ますこれを行う合理的な方法:

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

10

英語のみ、あなたは、Python、例えばの日時文字列のフォーマット方法を使用することができますについて

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

また、現在アクティブに言語で名前を返します。Djangoの方法を、使用することができます。 Djangoのテンプレートに

:Djangoのビュー関数で

{{ a_date|date('F') }} 

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

あなたは、例えばためジャンゴシェル(python manage.py shell)の後半をテストすることができスペイン語:

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' 
+0

をありがとうございましたここで最も完全な答え:) – Florian

0

月名が必要なテンプレートページにカスタムテンプレートタグを登録するのに役立つカスタムテンプレートタグを登録して解決しました。

templatetags/etras。PY

from django import template 
import calendar 

register = template.Library() 

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

テンプレートでの使用:彼らは考慮リクエストのロケールを取ることはありませんので、以下の回答の

{% load extras %} 
{{ month_figure|month_name }} 
関連する問題