DateTimeProperty の取扱い
データストアのモデル値型として DateTimeProperty(日付と時刻プロパティ)があります。当方ホームページ(Test Web Frames)では、トップページの更新情報で DateTimeProperty の値を表示させています。
このモデルクラスは以下のように定義してあります。
class History(db.Model): date = db.DateTimeProperty() comment = db.StringProperty()
datetime.datetimeクラスの初期化には、例えば次のようなものがあります。
datetime(year, month, day[, hour[, minute[, second[, microsecond[, tzinfo]]]]])
ここでは、以下のようにエンティティを作成しています。
history = History(key_name='1') history.date = datetime.datetime(2010, 7, 15, 9, 0, 0) history.comment = u'サイト開設しました' history.put()
トップページのRequestHandlerクラスでは以下のようなテンプレートを作成し、index.htmlに渡します。
def get(self): histories = db.GqlQuery("SELECT * FROM History" " ORDER BY date DESC LIMIT 3") if histories.count() <= 0: histories = None template_values = { (略) 'histories': histories, }
index.html では Django の組み込みテンプレートタグ/フィルタを用いて、template_values の histories を以下のように処理しています。
<div class="entry" ><h2>更新情報</h2> </div> <div class="section"> {% if histories %} {% for history in histories %} <p>{{ history.date }} : {{ history.comment }}</p> {% endfor %} {% else %} <p>更新情報はありません</p> {% endif %} </div>
このままでは DateTimeProperty 値が「年月日」だけでなく「時分秒」まで表示されて見た目に良くないため、date フィルタ(Django)で日付を「年月日」のみにフォーマットし直しています。
<p>{{ history.date|date:"Y-m-d" }} : {{ history.comment }}</p>
他にも、もし「年月日 時分 AM/PM」形式の書式が望みであれば以下のようにします。
<p>{{ history.date|date:"Y-m-d h:i A" }} : {{ history.comment }}</p>