如何使用Python + Django显示当前时间?

Luc*_*cas 19 python django google-app-engine

我正在学习如何使用Python和Django生成一个打印出当前时间的小型webapp.我正在使用Google App Engine.

现在它只显示一个空白页面,但我希望它显示当前时间.我也想将功能映射到主页..不是/时间/.

from django.http import HttpResponse
from django.conf.urls.defaults import *
import datetime

# returns current time in html
def current_datetime(request):
    now = datetime.datetime.now()
    html = "<html><body>It is now %s.</body></html>" % now
    return HttpResponse(html)

def main(): 
    # maps url to current_datetime func
    urlpatterns = patterns('',
        (r'^time/$', current_datetime),
    )

if __name__ == '__main__':
  main()
Run Code Online (Sandbox Code Playgroud)

Alv*_*oAV 37

也许这个文档对你有用:时区

格式化视图中的时间

您可以使用以下方式获取当前时间:

import datetime
now = datetime.datetime.now()
Run Code Online (Sandbox Code Playgroud)

根据时区获得时间:

import datetime
from django.utils.timezone import utc

now = datetime.datetime.utcnow().replace(tzinfo=utc)
Run Code Online (Sandbox Code Playgroud)

格式化你可以做的时间:

import datetime

now = datetime.datetime.now().strftime('%H:%M:%S')  #  Time like '23:12:05'
Run Code Online (Sandbox Code Playgroud)

格式化模板中的时间

你可以向模板发送一个日期时间,让我们从视图中向模板发送一个名为myDate的变量.你可以这样做来格式化这个日期时间:

{{ myDate | date:"D d M Y"}}  # Format Wed 09 Jan 2008
{{ myDate | date:"SHORT_DATE_FORMAT"}}  # Format 09/01/2008
{{ myDate | date:"d/m/Y"}}  # Format 09/01/2008
Run Code Online (Sandbox Code Playgroud)

检查模板过滤日期

我希望这对你有用


Sam*_*lan 13

使用now模板标记.例如:

{% now "jS F Y H:i" %}
Run Code Online (Sandbox Code Playgroud)

但是你需要在发送响应之前通过模板引擎发送你的字符串才能工作.


Y M*_*Y M 6

对于Django代码(不在模板中),支持实际上非常简单。

在设置中更改时区:

TIME_ZONE = 'Asia/Kolkata'
Run Code Online (Sandbox Code Playgroud)

在需要使用的地方,使用以下代码:

from django.utils import timezone
now = timezone.now()
Run Code Online (Sandbox Code Playgroud)

来源:https : //docs.djangoproject.com/en/2.1/topics/i18n/timezones/


A B*_*A B 0

您可以使用time.strftime()来打印当前时间。在您的 urlpatterns 中,只需更改'^time/$''^/$'即可将根页面映射到您的时间函数。