We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
DOC: "Invalid datetime unit in metadata string "[d]""
http://pandas-docs.github.io/pandas-docs-travis/timeseries.html#time-deltas-conversions

```
In [253]: to_timedelta(np.arange(5),unit='d')
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-253-bab05b276f33> in <module>()
----> 1 to_timedelta(np.arange(5),unit='d')

/home/travis/virtualenv/python2.7_with_system_site_packages/local/lib/python2.7/site-packages/pandas/tseries/timedeltas.pyc in to_timedelta(arg, box, unit)
     61         return Series(values, index=arg.index, name=arg.name, dtype='m8[ns]')
     62     elif is_list_like(arg):
---> 63         return _convert_listlike(arg, box=box, unit=unit)
     64 
     65     # ...so it must be a scalar value. Return scalar.

/home/travis/virtualenv/python2.7_with_system_site_packages/local/lib/python2.7/site-packages/pandas/tseries/timedeltas.pyc in _convert_listlike(arg, box, unit)
     42         elif is_integer_dtype(arg):
     43             # these are shortcutable
---> 44             value = arg.astype('timedelta64[{0}]'.format(unit)).astype('timedelta64[ns]')
     45         else:
     46             try:

TypeError: Invalid datetime unit in metadata string "[d]"
```


--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `pandas/tseries/timedeltas.py`
Content:
```
1 """
2 timedelta support tools
3 """
4 
5 import re
6 from datetime import timedelta
7 
8 import numpy as np
9 import pandas.tslib as tslib
10 from pandas import compat, _np_version_under1p7
11 from pandas.core.common import (ABCSeries, is_integer, is_integer_dtype, is_timedelta64_dtype,
12                                 _values_from_object, is_list_like, isnull)
13 
14 repr_timedelta = tslib.repr_timedelta64
15 repr_timedelta64 = tslib.repr_timedelta64
16 
17 def to_timedelta(arg, box=True, unit='ns'):
18     """
19     Convert argument to timedelta
20 
21     Parameters
22     ----------
23     arg : string, timedelta, array of strings (with possible NAs)
24     box : boolean, default True
25         If True returns a Series of the results, if False returns ndarray of values
26     unit : unit of the arg (D,h,m,s,ms,us,ns) denote the unit, which is an integer/float number
27 
28     Returns
29     -------
30     ret : timedelta64/arrays of timedelta64 if parsing succeeded
31     """
32     if _np_version_under1p7:
33         raise ValueError("to_timedelta is not support for numpy < 1.7")
34 
35     def _convert_listlike(arg, box, unit):
36 
37         if isinstance(arg, (list,tuple)):
38             arg = np.array(arg, dtype='O')
39 
40         if is_timedelta64_dtype(arg):
41             value = arg.astype('timedelta64[ns]')
42         elif is_integer_dtype(arg):
43             # these are shortcutable
44             value = arg.astype('timedelta64[{0}]'.format(unit)).astype('timedelta64[ns]')
45         else:
46             try:
47                 value = tslib.array_to_timedelta64(_ensure_object(arg),unit=unit)
48             except:
49                 value = np.array([ _coerce_scalar_to_timedelta_type(r, unit=unit) for r in arg ])
50 
51         if box:
52             from pandas import Series
53             value = Series(value,dtype='m8[ns]')
54         return value
55 
56     if arg is None:
57         return arg
58     elif isinstance(arg, ABCSeries):
59         from pandas import Series
60         values = _convert_listlike(arg.values, box=False, unit=unit)
61         return Series(values, index=arg.index, name=arg.name, dtype='m8[ns]')
62     elif is_list_like(arg):
63         return _convert_listlike(arg, box=box, unit=unit)
64 
65     # ...so it must be a scalar value. Return scalar.
66     return _coerce_scalar_to_timedelta_type(arg, unit=unit)
67 
68 _short_search = re.compile(
69     "^\s*(?P<neg>-?)\s*(?P<value>\d*\.?\d*)\s*(?P<unit>d|s|ms|us|ns)?\s*$",re.IGNORECASE)
70 _full_search = re.compile(
71     "^\s*(?P<neg>-?)\s*(?P<days>\d+)?\s*(days|d|day)?,?\s*(?P<time>\d{2}:\d{2}:\d{2})?(?P<frac>\.\d+)?\s*$",re.IGNORECASE)
72 _nat_search = re.compile(
73     "^\s*(nat|nan)\s*$",re.IGNORECASE)
74 _whitespace = re.compile('^\s*$')
75 
76 def _coerce_scalar_to_timedelta_type(r, unit='ns'):
77     """ convert strings to timedelta; coerce to np.timedelta64"""
78 
79     if isinstance(r, compat.string_types):
80 
81         # we are already converting to nanoseconds
82         converter = _get_string_converter(r, unit=unit)
83         r = converter()
84         unit='ns'
85 
86     return tslib.convert_to_timedelta(r,unit)
87 
88 def _get_string_converter(r, unit='ns'):
89     """ return a string converter for r to process the timedelta format """
90 
91     # treat as a nan
92     if _whitespace.search(r):
93         def convert(r=None, unit=None):
94             return tslib.iNaT
95         return convert
96 
97     m = _short_search.search(r)
98     if m:
99         def convert(r=None, unit=unit, m=m):
100             if r is not None:
101                 m = _short_search.search(r)
102 
103             gd = m.groupdict()
104 
105             r = float(gd['value'])
106             u = gd.get('unit')
107             if u is not None:
108                 unit = u.lower()
109             if gd['neg']:
110                 r *= -1
111             return tslib.cast_from_unit(r, unit)
112         return convert
113 
114     m = _full_search.search(r)
115     if m:
116         def convert(r=None, unit=None, m=m):
117             if r is not None:
118                 m = _full_search.search(r)
119 
120             gd = m.groupdict()
121 
122             # convert to seconds
123             value = float(gd['days'] or 0) * 86400
124 
125             time = gd['time']
126             if time:
127                 (hh,mm,ss) = time.split(':')
128                 value += float(hh)*3600 + float(mm)*60 + float(ss)
129 
130             frac = gd['frac']
131             if frac:
132                 value += float(frac)
133 
134             if gd['neg']:
135                 value *= -1
136             return tslib.cast_from_unit(value, 's')
137         return convert
138 
139     m = _nat_search.search(r)
140     if m:
141         def convert(r=None, unit=None, m=m):
142             return tslib.iNaT
143         return convert
144 
145     # no converter
146     raise ValueError("cannot create timedelta string converter for [{0}]".format(r))
147 
148 def _possibly_cast_to_timedelta(value, coerce=True):
149     """ try to cast to timedelta64, if already a timedeltalike, then make
150         sure that we are [ns] (as numpy 1.6.2 is very buggy in this regards,
151         don't force the conversion unless coerce is True
152 
153         if coerce='compat' force a compatibilty coercerion (to timedeltas) if needeed
154         """
155 
156     # coercion compatability
157     if coerce == 'compat' and _np_version_under1p7:
158 
159         def convert(td, dtype):
160 
161             # we have an array with a non-object dtype
162             if hasattr(td,'item'):
163                 td = td.astype(np.int64).item()
164                 if td == tslib.iNaT:
165                     return td
166                 if dtype == 'm8[us]':
167                     td *= 1000
168                 return td
169 
170             if isnull(td) or td == tslib.compat_NaT or td == tslib.iNaT:
171                 return tslib.iNaT
172 
173             # convert td value to a nanosecond value
174             d = td.days
175             s = td.seconds
176             us = td.microseconds
177 
178             if dtype == 'object' or dtype == 'm8[ns]':
179                 td = 1000*us + (s + d * 24 * 3600) * 10 ** 9
180             else:
181                 raise ValueError("invalid conversion of dtype in np < 1.7 [%s]" % dtype)
182 
183             return td
184 
185         # < 1.7 coercion
186         if not is_list_like(value):
187             value = np.array([ value ])
188 
189         dtype = value.dtype
190         return np.array([ convert(v,dtype) for v in value ], dtype='m8[ns]')
191 
192     # deal with numpy not being able to handle certain timedelta operations
193     if isinstance(value, (ABCSeries, np.ndarray)) and value.dtype.kind == 'm':
194         if value.dtype != 'timedelta64[ns]':
195             value = value.astype('timedelta64[ns]')
196         return value
197 
198     # we don't have a timedelta, but we want to try to convert to one (but
199     # don't force it)
200     if coerce:
201         new_value = tslib.array_to_timedelta64(
202             _values_from_object(value).astype(object), coerce=False)
203         if new_value.dtype == 'i8':
204             value = np.array(new_value, dtype='timedelta64[ns]')
205 
206     return value
207 
208
```
--- END FILES ---

Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.

Here is an example:

```diff
diff --git a/examples/server_async.py b/examples/server_async.py
--- a/examples/server_async.py
+++ b/examples/server_async.py
@@ -313,4 +313,4 @@
 
 
 if __name__ == "__main__":
-    asyncio.run(run_async_server("."), debug=True)
+    asyncio.run(run_async_server(), debug=True)
diff --git a/examples/server_sync.py b/examples/server_sync.py
--- a/examples/server_sync.py
+++ b/examples/server_sync.py
@@ -313,5 +313,5 @@
 
 
 if __name__ == "__main__":
-    server = run_sync_server(".")
+    server = run_sync_server()
     server.shutdown()

```

diff --git a/pandas/tseries/timedeltas.py b/pandas/tseries/timedeltas.py
--- a/pandas/tseries/timedeltas.py
+++ b/pandas/tseries/timedeltas.py
@@ -40,6 +40,8 @@
         if is_timedelta64_dtype(arg):
             value = arg.astype('timedelta64[ns]')
         elif is_integer_dtype(arg):
+            unit = _validate_timedelta_unit(unit)
+
             # these are shortcutable
             value = arg.astype('timedelta64[{0}]'.format(unit)).astype('timedelta64[ns]')
         else:
@@ -65,6 +67,15 @@
     # ...so it must be a scalar value. Return scalar.
     return _coerce_scalar_to_timedelta_type(arg, unit=unit)
 
+def _validate_timedelta_unit(arg):
+    """ provide validation / translation for timedelta short units """
+
+    if re.search("Y|W|D",arg,re.IGNORECASE) or arg == 'M':
+        return arg.upper()
+    elif re.search("h|m|s|ms|us|ns",arg,re.IGNORECASE):
+        return arg.lower()
+    raise ValueError("invalid timedelta unit {0} provided".format(arg))
+
 _short_search = re.compile(
     "^\s*(?P<neg>-?)\s*(?P<value>\d*\.?\d*)\s*(?P<unit>d|s|ms|us|ns)?\s*$",re.IGNORECASE)
 _full_search = re.compile(

{"golden_diff": "diff --git a/pandas/tseries/timedeltas.py b/pandas/tseries/timedeltas.py\n--- a/pandas/tseries/timedeltas.py\n+++ b/pandas/tseries/timedeltas.py\n@@ -40,6 +40,8 @@\n         if is_timedelta64_dtype(arg):\n             value = arg.astype('timedelta64[ns]')\n         elif is_integer_dtype(arg):\n+            unit = _validate_timedelta_unit(unit)\n+\n             # these are shortcutable\n             value = arg.astype('timedelta64[{0}]'.format(unit)).astype('timedelta64[ns]')\n         else:\n@@ -65,6 +67,15 @@\n     # ...so it must be a scalar value. Return scalar.\n     return _coerce_scalar_to_timedelta_type(arg, unit=unit)\n \n+def _validate_timedelta_unit(arg):\n+    \"\"\" provide validation / translation for timedelta short units \"\"\"\n+\n+    if re.search(\"Y|W|D\",arg,re.IGNORECASE) or arg == 'M':\n+        return arg.upper()\n+    elif re.search(\"h|m|s|ms|us|ns\",arg,re.IGNORECASE):\n+        return arg.lower()\n+    raise ValueError(\"invalid timedelta unit {0} provided\".format(arg))\n+\n _short_search = re.compile(\n     \"^\\s*(?P<neg>-?)\\s*(?P<value>\\d*\\.?\\d*)\\s*(?P<unit>d|s|ms|us|ns)?\\s*$\",re.IGNORECASE)\n _full_search = re.compile(\n", "issue": "DOC: \"Invalid datetime unit in metadata string \"[d]\"\"\nhttp://pandas-docs.github.io/pandas-docs-travis/timeseries.html#time-deltas-conversions\n\n```\nIn [253]: to_timedelta(np.arange(5),unit='d')\n---------------------------------------------------------------------------\nTypeError                                 Traceback (most recent call last)\n<ipython-input-253-bab05b276f33> in <module>()\n----> 1 to_timedelta(np.arange(5),unit='d')\n\n/home/travis/virtualenv/python2.7_with_system_site_packages/local/lib/python2.7/site-packages/pandas/tseries/timedeltas.pyc in to_timedelta(arg, box, unit)\n     61         return Series(values, index=arg.index, name=arg.name, dtype='m8[ns]')\n     62     elif is_list_like(arg):\n---> 63         return _convert_listlike(arg, box=box, unit=unit)\n     64 \n     65     # ...so it must be a scalar value. Return scalar.\n\n/home/travis/virtualenv/python2.7_with_system_site_packages/local/lib/python2.7/site-packages/pandas/tseries/timedeltas.pyc in _convert_listlike(arg, box, unit)\n     42         elif is_integer_dtype(arg):\n     43             # these are shortcutable\n---> 44             value = arg.astype('timedelta64[{0}]'.format(unit)).astype('timedelta64[ns]')\n     45         else:\n     46             try:\n\nTypeError: Invalid datetime unit in metadata string \"[d]\"\n```\n\n", "before_files": [{"content": "\"\"\"\ntimedelta support tools\n\"\"\"\n\nimport re\nfrom datetime import timedelta\n\nimport numpy as np\nimport pandas.tslib as tslib\nfrom pandas import compat, _np_version_under1p7\nfrom pandas.core.common import (ABCSeries, is_integer, is_integer_dtype, is_timedelta64_dtype,\n                                _values_from_object, is_list_like, isnull)\n\nrepr_timedelta = tslib.repr_timedelta64\nrepr_timedelta64 = tslib.repr_timedelta64\n\ndef to_timedelta(arg, box=True, unit='ns'):\n    \"\"\"\n    Convert argument to timedelta\n\n    Parameters\n    ----------\n    arg : string, timedelta, array of strings (with possible NAs)\n    box : boolean, default True\n        If True returns a Series of the results, if False returns ndarray of values\n    unit : unit of the arg (D,h,m,s,ms,us,ns) denote the unit, which is an integer/float number\n\n    Returns\n    -------\n    ret : timedelta64/arrays of timedelta64 if parsing succeeded\n    \"\"\"\n    if _np_version_under1p7:\n        raise ValueError(\"to_timedelta is not support for numpy < 1.7\")\n\n    def _convert_listlike(arg, box, unit):\n\n        if isinstance(arg, (list,tuple)):\n            arg = np.array(arg, dtype='O')\n\n        if is_timedelta64_dtype(arg):\n            value = arg.astype('timedelta64[ns]')\n        elif is_integer_dtype(arg):\n            # these are shortcutable\n            value = arg.astype('timedelta64[{0}]'.format(unit)).astype('timedelta64[ns]')\n        else:\n            try:\n                value = tslib.array_to_timedelta64(_ensure_object(arg),unit=unit)\n            except:\n                value = np.array([ _coerce_scalar_to_timedelta_type(r, unit=unit) for r in arg ])\n\n        if box:\n            from pandas import Series\n            value = Series(value,dtype='m8[ns]')\n        return value\n\n    if arg is None:\n        return arg\n    elif isinstance(arg, ABCSeries):\n        from pandas import Series\n        values = _convert_listlike(arg.values, box=False, unit=unit)\n        return Series(values, index=arg.index, name=arg.name, dtype='m8[ns]')\n    elif is_list_like(arg):\n        return _convert_listlike(arg, box=box, unit=unit)\n\n    # ...so it must be a scalar value. Return scalar.\n    return _coerce_scalar_to_timedelta_type(arg, unit=unit)\n\n_short_search = re.compile(\n    \"^\\s*(?P<neg>-?)\\s*(?P<value>\\d*\\.?\\d*)\\s*(?P<unit>d|s|ms|us|ns)?\\s*$\",re.IGNORECASE)\n_full_search = re.compile(\n    \"^\\s*(?P<neg>-?)\\s*(?P<days>\\d+)?\\s*(days|d|day)?,?\\s*(?P<time>\\d{2}:\\d{2}:\\d{2})?(?P<frac>\\.\\d+)?\\s*$\",re.IGNORECASE)\n_nat_search = re.compile(\n    \"^\\s*(nat|nan)\\s*$\",re.IGNORECASE)\n_whitespace = re.compile('^\\s*$')\n\ndef _coerce_scalar_to_timedelta_type(r, unit='ns'):\n    \"\"\" convert strings to timedelta; coerce to np.timedelta64\"\"\"\n\n    if isinstance(r, compat.string_types):\n\n        # we are already converting to nanoseconds\n        converter = _get_string_converter(r, unit=unit)\n        r = converter()\n        unit='ns'\n\n    return tslib.convert_to_timedelta(r,unit)\n\ndef _get_string_converter(r, unit='ns'):\n    \"\"\" return a string converter for r to process the timedelta format \"\"\"\n\n    # treat as a nan\n    if _whitespace.search(r):\n        def convert(r=None, unit=None):\n            return tslib.iNaT\n        return convert\n\n    m = _short_search.search(r)\n    if m:\n        def convert(r=None, unit=unit, m=m):\n            if r is not None:\n                m = _short_search.search(r)\n\n            gd = m.groupdict()\n\n            r = float(gd['value'])\n            u = gd.get('unit')\n            if u is not None:\n                unit = u.lower()\n            if gd['neg']:\n                r *= -1\n            return tslib.cast_from_unit(r, unit)\n        return convert\n\n    m = _full_search.search(r)\n    if m:\n        def convert(r=None, unit=None, m=m):\n            if r is not None:\n                m = _full_search.search(r)\n\n            gd = m.groupdict()\n\n            # convert to seconds\n            value = float(gd['days'] or 0) * 86400\n\n            time = gd['time']\n            if time:\n                (hh,mm,ss) = time.split(':')\n                value += float(hh)*3600 + float(mm)*60 + float(ss)\n\n            frac = gd['frac']\n            if frac:\n                value += float(frac)\n\n            if gd['neg']:\n                value *= -1\n            return tslib.cast_from_unit(value, 's')\n        return convert\n\n    m = _nat_search.search(r)\n    if m:\n        def convert(r=None, unit=None, m=m):\n            return tslib.iNaT\n        return convert\n\n    # no converter\n    raise ValueError(\"cannot create timedelta string converter for [{0}]\".format(r))\n\ndef _possibly_cast_to_timedelta(value, coerce=True):\n    \"\"\" try to cast to timedelta64, if already a timedeltalike, then make\n        sure that we are [ns] (as numpy 1.6.2 is very buggy in this regards,\n        don't force the conversion unless coerce is True\n\n        if coerce='compat' force a compatibilty coercerion (to timedeltas) if needeed\n        \"\"\"\n\n    # coercion compatability\n    if coerce == 'compat' and _np_version_under1p7:\n\n        def convert(td, dtype):\n\n            # we have an array with a non-object dtype\n            if hasattr(td,'item'):\n                td = td.astype(np.int64).item()\n                if td == tslib.iNaT:\n                    return td\n                if dtype == 'm8[us]':\n                    td *= 1000\n                return td\n\n            if isnull(td) or td == tslib.compat_NaT or td == tslib.iNaT:\n                return tslib.iNaT\n\n            # convert td value to a nanosecond value\n            d = td.days\n            s = td.seconds\n            us = td.microseconds\n\n            if dtype == 'object' or dtype == 'm8[ns]':\n                td = 1000*us + (s + d * 24 * 3600) * 10 ** 9\n            else:\n                raise ValueError(\"invalid conversion of dtype in np < 1.7 [%s]\" % dtype)\n\n            return td\n\n        # < 1.7 coercion\n        if not is_list_like(value):\n            value = np.array([ value ])\n\n        dtype = value.dtype\n        return np.array([ convert(v,dtype) for v in value ], dtype='m8[ns]')\n\n    # deal with numpy not being able to handle certain timedelta operations\n    if isinstance(value, (ABCSeries, np.ndarray)) and value.dtype.kind == 'm':\n        if value.dtype != 'timedelta64[ns]':\n            value = value.astype('timedelta64[ns]')\n        return value\n\n    # we don't have a timedelta, but we want to try to convert to one (but\n    # don't force it)\n    if coerce:\n        new_value = tslib.array_to_timedelta64(\n            _values_from_object(value).astype(object), coerce=False)\n        if new_value.dtype == 'i8':\n            value = np.array(new_value, dtype='timedelta64[ns]')\n\n    return value\n\n", "path": "pandas/tseries/timedeltas.py"}], "after_files": [{"content": "\"\"\"\ntimedelta support tools\n\"\"\"\n\nimport re\nfrom datetime import timedelta\n\nimport numpy as np\nimport pandas.tslib as tslib\nfrom pandas import compat, _np_version_under1p7\nfrom pandas.core.common import (ABCSeries, is_integer, is_integer_dtype, is_timedelta64_dtype,\n                                _values_from_object, is_list_like, isnull)\n\nrepr_timedelta = tslib.repr_timedelta64\nrepr_timedelta64 = tslib.repr_timedelta64\n\ndef to_timedelta(arg, box=True, unit='ns'):\n    \"\"\"\n    Convert argument to timedelta\n\n    Parameters\n    ----------\n    arg : string, timedelta, array of strings (with possible NAs)\n    box : boolean, default True\n        If True returns a Series of the results, if False returns ndarray of values\n    unit : unit of the arg (D,h,m,s,ms,us,ns) denote the unit, which is an integer/float number\n\n    Returns\n    -------\n    ret : timedelta64/arrays of timedelta64 if parsing succeeded\n    \"\"\"\n    if _np_version_under1p7:\n        raise ValueError(\"to_timedelta is not support for numpy < 1.7\")\n\n    def _convert_listlike(arg, box, unit):\n\n        if isinstance(arg, (list,tuple)):\n            arg = np.array(arg, dtype='O')\n\n        if is_timedelta64_dtype(arg):\n            value = arg.astype('timedelta64[ns]')\n        elif is_integer_dtype(arg):\n            unit = _validate_timedelta_unit(unit)\n\n            # these are shortcutable\n            value = arg.astype('timedelta64[{0}]'.format(unit)).astype('timedelta64[ns]')\n        else:\n            try:\n                value = tslib.array_to_timedelta64(_ensure_object(arg),unit=unit)\n            except:\n                value = np.array([ _coerce_scalar_to_timedelta_type(r, unit=unit) for r in arg ])\n\n        if box:\n            from pandas import Series\n            value = Series(value,dtype='m8[ns]')\n        return value\n\n    if arg is None:\n        return arg\n    elif isinstance(arg, ABCSeries):\n        from pandas import Series\n        values = _convert_listlike(arg.values, box=False, unit=unit)\n        return Series(values, index=arg.index, name=arg.name, dtype='m8[ns]')\n    elif is_list_like(arg):\n        return _convert_listlike(arg, box=box, unit=unit)\n\n    # ...so it must be a scalar value. Return scalar.\n    return _coerce_scalar_to_timedelta_type(arg, unit=unit)\n\ndef _validate_timedelta_unit(arg):\n    \"\"\" provide validation / translation for timedelta short units \"\"\"\n\n    if re.search(\"Y|W|D\",arg,re.IGNORECASE) or arg == 'M':\n        return arg.upper()\n    elif re.search(\"h|m|s|ms|us|ns\",arg,re.IGNORECASE):\n        return arg.lower()\n    raise ValueError(\"invalid timedelta unit {0} provided\".format(arg))\n\n_short_search = re.compile(\n    \"^\\s*(?P<neg>-?)\\s*(?P<value>\\d*\\.?\\d*)\\s*(?P<unit>d|s|ms|us|ns)?\\s*$\",re.IGNORECASE)\n_full_search = re.compile(\n    \"^\\s*(?P<neg>-?)\\s*(?P<days>\\d+)?\\s*(days|d|day)?,?\\s*(?P<time>\\d{2}:\\d{2}:\\d{2})?(?P<frac>\\.\\d+)?\\s*$\",re.IGNORECASE)\n_nat_search = re.compile(\n    \"^\\s*(nat|nan)\\s*$\",re.IGNORECASE)\n_whitespace = re.compile('^\\s*$')\n\ndef _coerce_scalar_to_timedelta_type(r, unit='ns'):\n    \"\"\" convert strings to timedelta; coerce to np.timedelta64\"\"\"\n\n    if isinstance(r, compat.string_types):\n\n        # we are already converting to nanoseconds\n        converter = _get_string_converter(r, unit=unit)\n        r = converter()\n        unit='ns'\n\n    return tslib.convert_to_timedelta(r,unit)\n\ndef _get_string_converter(r, unit='ns'):\n    \"\"\" return a string converter for r to process the timedelta format \"\"\"\n\n    # treat as a nan\n    if _whitespace.search(r):\n        def convert(r=None, unit=None):\n            return tslib.iNaT\n        return convert\n\n    m = _short_search.search(r)\n    if m:\n        def convert(r=None, unit=unit, m=m):\n            if r is not None:\n                m = _short_search.search(r)\n\n            gd = m.groupdict()\n\n            r = float(gd['value'])\n            u = gd.get('unit')\n            if u is not None:\n                unit = u.lower()\n            if gd['neg']:\n                r *= -1\n            return tslib.cast_from_unit(r, unit)\n        return convert\n\n    m = _full_search.search(r)\n    if m:\n        def convert(r=None, unit=None, m=m):\n            if r is not None:\n                m = _full_search.search(r)\n\n            gd = m.groupdict()\n\n            # convert to seconds\n            value = float(gd['days'] or 0) * 86400\n\n            time = gd['time']\n            if time:\n                (hh,mm,ss) = time.split(':')\n                value += float(hh)*3600 + float(mm)*60 + float(ss)\n\n            frac = gd['frac']\n            if frac:\n                value += float(frac)\n\n            if gd['neg']:\n                value *= -1\n            return tslib.cast_from_unit(value, 's')\n        return convert\n\n    m = _nat_search.search(r)\n    if m:\n        def convert(r=None, unit=None, m=m):\n            return tslib.iNaT\n        return convert\n\n    # no converter\n    raise ValueError(\"cannot create timedelta string converter for [{0}]\".format(r))\n\ndef _possibly_cast_to_timedelta(value, coerce=True):\n    \"\"\" try to cast to timedelta64, if already a timedeltalike, then make\n        sure that we are [ns] (as numpy 1.6.2 is very buggy in this regards,\n        don't force the conversion unless coerce is True\n\n        if coerce='compat' force a compatibilty coercerion (to timedeltas) if needeed\n        \"\"\"\n\n    # coercion compatability\n    if coerce == 'compat' and _np_version_under1p7:\n\n        def convert(td, dtype):\n\n            # we have an array with a non-object dtype\n            if hasattr(td,'item'):\n                td = td.astype(np.int64).item()\n                if td == tslib.iNaT:\n                    return td\n                if dtype == 'm8[us]':\n                    td *= 1000\n                return td\n\n            if isnull(td) or td == tslib.compat_NaT or td == tslib.iNaT:\n                return tslib.iNaT\n\n            # convert td value to a nanosecond value\n            d = td.days\n            s = td.seconds\n            us = td.microseconds\n\n            if dtype == 'object' or dtype == 'm8[ns]':\n                td = 1000*us + (s + d * 24 * 3600) * 10 ** 9\n            else:\n                raise ValueError(\"invalid conversion of dtype in np < 1.7 [%s]\" % dtype)\n\n            return td\n\n        # < 1.7 coercion\n        if not is_list_like(value):\n            value = np.array([ value ])\n\n        dtype = value.dtype\n        return np.array([ convert(v,dtype) for v in value ], dtype='m8[ns]')\n\n    # deal with numpy not being able to handle certain timedelta operations\n    if isinstance(value, (ABCSeries, np.ndarray)) and value.dtype.kind == 'm':\n        if value.dtype != 'timedelta64[ns]':\n            value = value.astype('timedelta64[ns]')\n        return value\n\n    # we don't have a timedelta, but we want to try to convert to one (but\n    # don't force it)\n    if coerce:\n        new_value = tslib.array_to_timedelta64(\n            _values_from_object(value).astype(object), coerce=False)\n        if new_value.dtype == 'i8':\n            value = np.array(new_value, dtype='timedelta64[ns]')\n\n    return value\n\n", "path": "pandas/tseries/timedeltas.py"}]}