Format timedelta in Django template

Asked

Viewed 33 times

0

I’m having trouble presenting the uptime time of an equipment, Django automatically shows in the following format:

inserir a descrição da imagem aqui

I would like to present this time value in Portuguese.

in the settings.py Timezone settings are as follows:

LANGUAGE_CODE = 'pt-br'

LOCALE_NAME = 'pt_BR'

TIME_ZONE = 'America/Sao_Paulo'

USE_I18N = True

USE_L10N = True

USE_TZ = True

the template looks like this:

<tr>
    <td>Uptime:</td>
    <td>{{ status.uptime }}</td>
</tr>

and the value shown is obtained in this way:

obj['uptime'] = (datetime.now().replace(microsecond=0) - obj['last_up'])

Thanks in advance for your attention.

  • What type of variable is being passed to the template? How is the template?

  • the template looks like this: <tr> <td>Uptime:</td> <td>{{ status.uptime }}</td> </tr> and the value shown is obtained like this: obj['uptime'] = (datetime.now(). replace(microsecond=0) - obj['last_up'])

  • updates your post with code

1 answer

0


I solved by creating the following function:

uptime = (datetime.now().replace(microsecond=0) - obj['last_up'])
obj['uptime'] = format_uptime(uptime)

def format_uptime(timedelta):
    total_seconds = timedelta.seconds

    days = total_seconds // (60 * 60 * 24)
    total_seconds = total_seconds % (60 * 60 * 24)
    hours = total_seconds // (60 * 60)
    total_seconds = total_seconds % (60 * 60)
    minutes = total_seconds // 60
    seconds = total_seconds % 60

    if days > 0:
        return f'{days} Dias {hours}h {minutes}m {seconds}s'
    else:
        return f'{hours}h {minutes}m {seconds}s'

Browser other questions tagged

You are not signed in. Login or sign up in order to post.