Wagh
Wagh

Reputation: 4306

Get the date in days hours and minute since in django template

I want to get date in day hours and minute in django template.

my view.py

from django.utils import timezone    
def get_user_specific_android_crave_one(request):

    if request.method=="GET":
        craves1=CraveData.objects.all().count()
        if craves1==0:

            html = render_to_string('crave/ajax/nocrave.html')
            print html
            return HttpResponse(html,mimetype="application/text")
        else:
            craves=list(CraveData.objects.all().order_by("-date"))                
            #fbUser = FacebookUser.objects.get(person=request.user)
            #print fbUser.image                        
            for crave in craves:
                #fbUser = FacebookUser.objects.get(person=CraveData.facebookuser)
                print crave
                nc = timezone.now()
                cc = crave.date
                dc = nc-cc
                secc=dc.seconds
                hours = secc // 3600
                secc = secc - (hours * 3600)
                minutes = secc // 60
                lastc = '%s hours %s minutes ago' % (hours, minutes)
                reply= list(Comment.objects.filter(crave=crave))
                print reply
                for repl in reply:
                crave.reply = reply
                html = render_to_string('crave/ajax/crave.html',{"craves":craves,"lastc":lastc})
                return HttpResponse(html,mimetype="application/json")

my crave.html is

<div>{% for crave in craves  %}
{{crave.person}}{{ crave }}<br/>
{{lastc}}<!--------- To get date in days hours and minute format since crave made--------->
 {% endfor %}
</div>

Here i am getting time but for all crave i am getting same tome like "Two hours 10 minutes ago" Its same for all crave because i am getting the same variable value from view. I want to know in template how to convert standered date format of django to date format i want. I am getting proper date for each crave using {{crave.time}}. But this is standered format by django. I want to display like 1 day ago, 2 hours ago, 20 minutes ago depending on the time crave made. I searche a lot on net but not got relavent data. please help me out.

Upvotes: 3

Views: 1957

Answers (1)

trnsnt
trnsnt

Reputation: 694

You can user naturaltime, here is the Django documentation. A short example:

{% load humanize %}
{{ datimeobject|naturaltime }}

It will display something like 29 seconds ago or 1 week, 2 days from now.

Note that you need to load humanize

Upvotes: 4

Related Questions