Mehak
Mehak

Reputation: 961

Change format for Duration field in django admin

I'm using django DurationField in a model to calculate the time difference between two DateTimeField.

On the admin site for that model, the field shows up like this:

# short duration
Cumulative Total time:   0:51:33
# longer duration
Cumulative Total time:   2 days, 3:10:21

Is it possible to change the format for this field to the below given format?

Cumulative Total time:   2 days, 3 hours, 10 minutes, 21 seconds

Upvotes: 5

Views: 6935

Answers (2)

Michał Darowny
Michał Darowny

Reputation: 414

If you are using Serializer and DurationField you have to change value_to_string() to to_representation()

class DurationField(Field):
    ...
    def to_representation(self, value):
       return duration_string(value)

where duration_string() has the same implementation as above

Upvotes: 0

Ralf
Ralf

Reputation: 16505

The DurationField has the following code that relates to formatting:

...
from django.utils.duration import duration_string
...

class DurationField(Field):
    ...
    def value_to_string(self, obj):
        val = self.value_from_object(obj)
        return '' if val is None else duration_string(val)

and the function duration_string looks like this:

def duration_string(duration):
    """Version of str(timedelta) which is not English specific."""
    days, hours, minutes, seconds, microseconds = _get_duration_components(duration)

    string = '{:02d}:{:02d}:{:02d}'.format(hours, minutes, seconds)
    if days:
        string = '{} '.format(days) + string
    if microseconds:
        string += '.{:06d}'.format(microseconds)

    return string

One solution is to create your custom field that overrides the one method listed above:

from django.utils.duration import _get_duration_components

class CustomDurationField(DurationField):
    def value_to_string(self, obj):
        val = self.value_from_object(obj)
        if val is None:
            return ''

        days, hours, minutes, seconds, microseconds = _get_duration_components(val)
        return '{} days, {:02d} hours, {:02d} minutes, {:02d}.{:06d} seconds'.format(
            days, hours, minutes, seconds, microseconds)

You would need to tweak the exact output to fit your requirements.

Upvotes: 8

Related Questions