Opened 8 years ago

Closed 8 years ago

#27699 closed Bug (fixed)

parse_duration returns None if passed a string with a negative number of seconds

Reported by: Filipe L B Correia Owned by: hardik1997
Component: Utilities Version: 1.10
Severity: Normal Keywords: parse_duration, DurationField
Cc: hardik1997 Triage Stage: Accepted
Has patch: yes Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no

Description

For instance, parse_duration('172800') correctly returns timedelta(2) (2 days), while parse_duration('-172800') incorrectly returns None instead of timedelta(-2) (-2 days).

This particularly affects the DurationField in SQLite3, since it parse_duration is used to read the value from the database, and a negative duration is stored as a negative number.

I would suggest adding an optional minus sign in to the seconds pattern (maybe also for the hours and minutes?), as there is for the days pattern:

standard_duration_re = re.compile(
    r'^'
    r'(?:(?P<days>-?\d+) (days?, )?)?'
    r'((?:(?P<hours>\d+):)(?=\d+:\d+))?'
    r'(?:(?P<minutes>\d+):)?'
    r'(?P<seconds>-?\d+)'
    r'(?:\.(?P<microseconds>\d{1,6})\d{0,6})?'
    r'$'
)

Or have an alternative pattern:

negative_seconds_duration_re = re.compile(
    r'^'
    r'(?P<seconds>-\d+)'
    r'$'
)

If the current behavior is indeed the intended behavior for the parse_duration function, then one should fix the db.backends.base.operations.convert_durationfield_value function to handle a negative value for the DurationField.

Change History (5)

comment:1 by hardik1997, 8 years ago

Owner: changed from nobody to hardik1997
Status: newassigned

comment:2 by hardik1997, 8 years ago

Cc: hardik1997 added

comment:3 by Jinank Jain, 8 years ago

I have added on PR could someone please review it. https://github.com/django/django/pull/7814

comment:4 by Tim Graham, 8 years ago

Has patch: set
Triage Stage: UnreviewedAccepted

Another PR from hardik1997. Jinank, for future reference, please observe if a ticket is assigned to prevent duplicate work. If a ticket goes without activity for weeks, feel free to reassign.

comment:5 by Claude Paroz <claude@…>, 8 years ago

Resolution: fixed
Status: assignedclosed

In f4c0eec7:

Fixed #27699 -- Added negative timedelta support to parse_duration()

Note: See TracTickets for help on using tickets.
Back to Top