Opened 7 months ago

Closed 7 months ago

Last modified 7 months ago

#33349 closed New feature (wontfix)

Add option to produce duration_string without days

Reported by: Claude Paroz Owned by: nobody
Component: Forms Version: dev
Severity: Normal Keywords:
Cc: Triage Stage: Unreviewed
Has patch: no Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no

Description

I have a form with a custom field (inheriting from Django's DurationField) allowing to input duration in the form "hh:mm".

However, when user inputs durations > "23:59", re-displaying those durations is kind of broken ("1 ..."). Customizing prepare_value is rather straightforward, however I'd like to avoid rewriting the whole django.utils.duration.duration_string. If that function would accept a use_days argument, it would be a lot easier to achieve my use case.

Change History (3)

comment:1 Changed 7 months ago by Mariusz Felisiak

Resolution: wontfix
Status: newclosed

Thanks for this ticket, however duration_string is a private undocumented API and I don't think that adding a new option is justified here. You can also re-use _get_duration_components to simplify your implementation, e.g.:

def custom_duration_string(duration):
    days, hours, minutes, seconds, microseconds = _get_duration_components(duration)
    if days:
        hours += days * 24
    string = '{:02d}:{:02d}:{:02d}'.format(hours, minutes, seconds)
    if microseconds:
        string += '.{:06d}'.format(microseconds)
    return string

comment:2 Changed 7 months ago by Claude Paroz

OK, thanks for the code proposal.

comment:3 Changed 7 months ago by Claude Paroz

For my use case, I think the shorter would be:

    def prepare_value(self, value):
        if isinstance(value, datetime.timedelta):
            seconds = value.days * 24 * 3600 + value.seconds
            hours = seconds // 3600
            minutes = seconds % 3600 // 60
            value = '{:02d}:{:02d}'.format(hours, minutes)
        return value
Note: See TracTickets for help on using tickets.
Back to Top