Django:如何在视图中获取格式日期? [英] Django: how to get format date in views?

查看:394
本文介绍了Django:如何在视图中获取格式日期?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要使用SHORT_DATETIME_FORMAT。

I need to use SHORT_DATETIME_FORMAT in view.

def manage_list(request):

    user = User.objects.filter().order_by('date_joined') 
    usrs = [] 
    for usr in user: 
        usrs.append({
            _('First name'):  usr.first_name, 
            _('Last name'):   usr.last_name,
            _('Email'):       usr.email,
            _('Active'):      usr.is_active,
            _('Superuser'):   usr.is_superuser,
            _('Staff'):       usr.is_staff,
            _('Joined date'): usr.date_joined.strftime(SHORT_DATETIME_FORMAT),    
        }) 

    data = simplejson.dumps(usrs, indent=4)
    return HttpResponse(data, mimetype='application/json')

usr.date_joined有一种类型的日期字段我认为。我想根据django语言环境格式化此数据。所以这个字符串可能应该有帮助。我知道有一个模板过滤器,这样做,我想,但我想格式化usr.date_joined 仅在视图 - 保存django选择区域设置。

usr.date_joined has a type of "date field" I think. I want to format this data according to django locale. so this string probably should help. I know that there's a template filter which does that I wan, but I want to format usr.date_joined in view only - saving django choosen locale.

如果还有其他方法可以提供示例。最后我只想根据django locale的日期和时间显示一个格式的日期,我认为这个常数应该是这样的名字。..

If there's any other methods to do this please provide examples. in the end I just wanna have a formated date according to django locale which shows only date and time, I think this constant should do what the name says..

推荐答案

django.utils.formats 模块是您正在寻找的。我可以在文档中找到的唯一参考信息是 Django 1.2发行说明

The django.utils.formats module is what you're looking for. The only reference I could find in the docs was in the Django 1.2 release notes.

请记住,只有在 USE_L10N 设置为 True 。您可以使用date_format如下。

Remember that the localisation will only work if the USE_L10N setting is True. You can use the date_format as follows.

from datetime import datetime
from django.utils import formats
date_joined = datetime.now()
formatted_datetime = formats.date_format(date_joined, "SHORT_DATETIME_FORMAT")

这篇关于Django:如何在视图中获取格式日期?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆