Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Merged
merged 1 commit into from Jan 14, 2017
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
8 changes: 5 additions & 3 deletions django/utils/dateparse.py
Expand Up @@ -30,9 +30,9 @@
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<hours>-?\d+):)(?=\d+:\d+))?'
r'(?:(?P<minutes>-?\d+):)?'
r'(?P<seconds>-?\d+)'
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Tests are passing with only this line modified. Are the other changes needed? If so, add tests for them.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@timgraham I will update the PR with some more tests

r'(?:\.(?P<microseconds>\d{1,6})\d{0,6})?'
r'$'
)
Expand Down Expand Up @@ -125,5 +125,7 @@ def parse_duration(value):
sign = -1 if kw.pop('sign', '+') == '-' else 1
if kw.get('microseconds'):
kw['microseconds'] = kw['microseconds'].ljust(6, '0')
if kw.get('seconds') and kw.get('microseconds') and kw['seconds'].startswith('-'):
kw['microseconds'] = '-' + kw['microseconds']
kw = {k: float(v) for k, v in six.iteritems(kw) if v is not None}
return sign * datetime.timedelta(**kw)
4 changes: 4 additions & 0 deletions tests/utils_tests/test_dateparse.py
Expand Up @@ -108,6 +108,10 @@ def test_fractions_of_seconds(self):

def test_negative(self):
self.assertEqual(parse_duration('-4 15:30'), timedelta(days=-4, minutes=15, seconds=30))
self.assertEqual(parse_duration('-172800'), timedelta(days=-2))
self.assertEqual(parse_duration('-15:30'), timedelta(minutes=-15, seconds=30))
self.assertEqual(parse_duration('-1:15:30'), timedelta(hours=-1, minutes=15, seconds=30))
self.assertEqual(parse_duration('-30.1'), timedelta(seconds=-30, milliseconds=-100))

def test_iso_8601(self):
self.assertIsNone(parse_duration('P4Y'))
Expand Down