0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【Django】№02.現在時刻datetime.nowの表示方法をview内で変更してテンプレートに表示させる

Posted at

経緯

view.py内でdatetime.nowで現在時刻を取得し、それをajaxでテンプレートに表示させるというところまでは№01で実装できた。今度はその表示形式を変更したい。

 

採用した方法と条件

・django.utils.dateformat.formatで日時の文字列表現をするという方法を採用
・現在の表示は「2020/09/04 09:27:0513598」
・目的の表示は「2020年09月04日 金曜日 09:27:05」

 

今回不採用にした方法

strftime 関数に任意のフォーマット文字列を渡すことで、同じ datetime オブジェクトから様々の形にフォーマットする方法

参考)https://python.keicode.com/lang/format-datetime.php

record_app/views.py
class c_AjaxView(View):
    def get(self, request):
        d = datetime.datetime.now()  # ここで一旦現在時刻を呼び出す
        dt_now = d.strftime('%Y/%m/%d %A %H:%M:%S') # その現在時刻の表記を変更する
        return HttpResponse(dt_now,request)     # 表記を変更した変数を渡す
i_ajax = c_AjaxView.as_view()

⇒この場合、「2020/09/04 Friday 09:27:05」と表示された。(もともとは、2020/09/04 09:27:0513598だった)

⇒できれば日本語で表示したい。/を年に変更してもダメだった(何も表示されなくなった)

 

今回採用した方法は、
django.utils.dateformat.formatを使用する方法

参考)https://tokibito.hatenablog.com/entry/20110916/1316133659

record_app/views.py
from django.utils import dateformat  #変更①

class c_AjaxView(View):
    def get(self, request):
        d = datetime.datetime.now()
        dt_now =dateformat.format(d, 'Y年n月d日 l H:i:s') #変更② (lは、エルの小文字。曜日を表す。「曜日」を付けなくてもいい)
        return HttpResponse(dt_now,request)
i_ajax = c_AjaxView.as_view()

⇒ 2020年09月04日 金曜日 09:27:05 と表示された!!

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?