Displaying a timedelta object in a django template

故事扮演 提交于 2019-12-06 17:16:26

问题


I'm having trouble getting my django template to display a timedelta object consistently. I tried using the time filter in my template, but nothing is displayed when I do this. The timedelta object is shown as follows on the errors page if I use Assert False:

time    datetime.timedelta(0, 38, 132827)

This displays the time difference as:

0:00:38.132827

I would like to only show the hours, minutes, and seconds for each timedelta object. Does anyone have any suggestions on how I can do this?


回答1:


I followed Peter's advice and wrote a custom template filter.

Here's the steps I took.

First I followed this guide to create a custom template filter.

Be sure to read this section on code layout.

Here's my filter code

from django import template

register = template.Library()

@register.filter()
def smooth_timedelta(timedeltaobj):
    """Convert a datetime.timedelta object into Days, Hours, Minutes, Seconds."""
    secs = timedeltaobj.total_seconds()
    timetot = ""
    if secs > 86400: # 60sec * 60min * 24hrs
        days = secs // 86400
        timetot += "{} days".format(int(days))
        secs = secs - days*86400

    if secs > 3600:
        hrs = secs // 3600
        timetot += " {} hours".format(int(hrs))
        secs = secs - hrs*3600

    if secs > 60:
        mins = secs // 60
        timetot += " {} minutes".format(int(mins))
        secs = secs - mins*60

    if secs > 0:
        timetot += " {} seconds".format(int(secs))
    return timetot

Then in my template I did

{% load smooth_timedelta %}

{% timedeltaobject|smooth_timedelta %}

Example output




回答2:


You can try remove the microseconds from the timedelta object, before sending it to the template:

time = time - datetime.timedelta(microseconds=time.microseconds)



回答3:


I don't think there's anything built in, and timedeltas don't directly expose their hour and minute values. but this package includes a timedelta custom filter tag that might help: http://pydoc.net/django-timedeltafield/0.7.10/




回答4:


As far as I know you have to write you're own template tag for this. Below is the one I've concocted based on the Django core timesince/timeuntil code that should output what you're after:

@register.simple_tag
def duration( duration ):
"""
Usage: {% duration timedelta %}
Returns seconds duration as weeks, days, hours, minutes, seconds
Based on core timesince/timeuntil
"""

    def seconds_in_units(seconds):
    """
    Returns a tuple containing the most appropriate unit for the
    number of seconds supplied and the value in that units form.

    >>> seconds_in_units(7700)
    (2, 'hour')
    """

        unit_totals = OrderedDict()

        unit_limits = [
                       ("week", 7 * 24 * 3600),
                       ("day", 24 * 3600),
                       ("hour", 3600),
                       ("minute", 60),
                       ("second", 1)
                        ]

        for unit_name, limit in unit_limits:
            if seconds >= limit:
                amount = int(float(seconds) / limit)
                if amount != 1:
                    unit_name += 's' # dodgy pluralisation
                unit_totals[unit_name] = amount
                seconds = seconds - ( amount * limit )

        return unit_totals;


if duration:
    if isinstance( duration, datetime.timedelta ):
        if duration.total_seconds > 0:
            unit_totals = seconds_in_units( duration.total_seconds() )
            return ', '.join([str(v)+" "+str(k) for (k,v) in unit_totals.iteritems()])

return 'None'



回答5:


from datetime import datetime

start = datetime.now()

taken = datetime.now() - start

str(taken)

'0:03:08.243773'

str(taken).split('.')[0]

'0:03:08'


来源:https://stackoverflow.com/questions/16348003/displaying-a-timedelta-object-in-a-django-template

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