Skip to content

Commit 0a1e22b

Browse files
GH9570 allow timedelta string conversion without leading zero
1 parent 3e7f21c commit 0a1e22b

File tree

3 files changed

+12
-4
lines changed

3 files changed

+12
-4
lines changed

doc/source/whatsnew/v0.16.1.txt

+2
Original file line numberDiff line numberDiff line change
@@ -50,6 +50,8 @@ Enhancements
5050
- Allow conversion of values with dtype ``datetime64`` or ``timedelta64`` to strings using ``astype(str)`` (:issue:`9757`)
5151
- ``get_dummies`` function now accepts ``sparse`` keyword. If set to ``True``, the return ``DataFrame`` is sparse, e.g. ``SparseDataFrame``. (:issue:`8823`)
5252

53+
- Allow timedelta string conversion when leading zero is missing from time definition, ie `0:00:00` vs `00:00:00`. (:issue:`9570`)
54+
5355
.. _whatsnew_0161.api:
5456

5557
API changes

pandas/tseries/tests/test_timedeltas.py

+7
Original file line numberDiff line numberDiff line change
@@ -64,6 +64,13 @@ def test_construction(self):
6464
self.assertEqual(Timedelta(123072001000000).value, 123072001000000)
6565
self.assertTrue('1 days 10:11:12.001' in str(Timedelta(123072001000000)))
6666

67+
# string conversion with/without leading zero
68+
# GH 9570
69+
self.assertEqual(Timedelta('0:00:00'), timedelta(hours=0))
70+
self.assertEqual(Timedelta('00:00:00'), timedelta(hours=0))
71+
self.assertEqual(Timedelta('-1:00:00'), -timedelta(hours=1))
72+
self.assertEqual(Timedelta('-01:00:00'), -timedelta(hours=1))
73+
6774
# more strings
6875
# GH 8190
6976
self.assertEqual(Timedelta('1 h'), timedelta(hours=1))

pandas/tseries/timedeltas.py

+3-4
Original file line numberDiff line numberDiff line change
@@ -119,7 +119,7 @@ def _validate_timedelta_unit(arg):
119119
_short_search = re.compile(
120120
"^\s*(?P<neg>-?)\s*(?P<value>\d*\.?\d*)\s*(?P<unit>d|s|ms|us|ns)?\s*$",re.IGNORECASE)
121121
_full_search = re.compile(
122-
"^\s*(?P<neg>-?)\s*(?P<days>\d*\.?\d*)?\s*(days|d|day)?,?\s*\+?(?P<time>\d{2}:\d{2}:\d{2})?(?P<frac>\.\d+)?\s*$",re.IGNORECASE)
122+
"^\s*(?P<neg>-?)\s*(?P<days>\d*?\.?\d*?)?\s*(days|d|day)?,?\s*\+?(?P<time>\d{1,2}:\d{2}:\d{2})?(?P<frac>\.\d+)?\s*$",re.IGNORECASE)
123123
_nat_search = re.compile(
124124
"^\s*(nat|nan)\s*$",re.IGNORECASE)
125125
_whitespace = re.compile('^\s*$')
@@ -209,13 +209,12 @@ def convert(r=None, unit=None, m=m):
209209
is_neg = gd['neg']
210210
if gd['days']:
211211
days = int((float(gd['days'] or 0) * 86400)*1e9)
212-
if gd['neg']:
212+
if is_neg:
213213
days *= -1
214214
value += days
215215
else:
216-
if gd['neg']:
216+
if is_neg:
217217
value *= -1
218-
219218
return tslib.cast_from_unit(value, 'ns')
220219
return convert
221220

0 commit comments

Comments
 (0)