Opened 9 years ago
Closed 9 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 , 9 years ago
| Owner: | changed from to |
|---|---|
| Status: | new → assigned |
comment:2 by , 9 years ago
| Cc: | added |
|---|
comment:3 by , 9 years ago
comment:4 by , 9 years ago
| Has patch: | set |
|---|---|
| Triage Stage: | Unreviewed → Accepted |
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.
I have added on PR could someone please review it. https://github.com/django/django/pull/7814