Django: how to get format date in views?

人走茶凉 提交于 2019-12-18 11:41:11

问题


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 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.

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..


回答1:


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.

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")



回答2:


You might want to try using django.utils.dateformat.DateFormat

>>> from datetime import datetime
>>> dt = datetime.now()
>>> from django.utils.dateformat import DateFormat
>>> from django.utils.formats import get_format
>>> df = DateFormat(dt)
>>> df.format(get_format('DATE_FORMAT'))
u'April 23, 2013'
>>> df.format('Y-m-d')
u'2013-04-23'

More information using Python:

import django
help(django.utils.dateformat)



回答3:


To use the Django date filter in a view use defaultfilters, e.g.:

from django.template import defaultfilters

formatted_date = defaultfilters.date(usr.date_joined, "SHORT_DATETIME_FORMAT")



回答4:


Use localize shortcut.

>>> from django.utils.formats import localize
>>> from datetime import datetime
>>>
>>> print(datetime.now())
2016-12-18 19:30:35.786818
>>> print(localize(datetime.now()))
18 декабря 2016 г. 19:30



回答5:


from django.utils.formats import date_format

date_format(usr.date_joined)


来源:https://stackoverflow.com/questions/8287883/django-how-to-get-format-date-in-views

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!