Skip to content

Commit e65eed5

Browse files
jbrockmendelvictor
authored and
victor
committed
Finish moving period_helper to cython (pandas-dev#22196)
1 parent f4e7012 commit e65eed5

File tree

1 file changed

+31
-46
lines changed

1 file changed

+31
-46
lines changed

pandas/_libs/tslibs/timedeltas.pyx

+31-46
Original file line numberDiff line numberDiff line change
@@ -162,7 +162,7 @@ cpdef convert_to_timedelta64(object ts, object unit):
162162
if ts.astype('int64') == NPY_NAT:
163163
return np.timedelta64(NPY_NAT)
164164
elif is_timedelta64_object(ts):
165-
ts = ts.astype("m8[{0}]".format(unit.lower()))
165+
ts = ts.astype("m8[{unit}]".format(unit=unit.lower()))
166166
elif is_integer_object(ts):
167167
if ts == NPY_NAT:
168168
return np.timedelta64(NPY_NAT)
@@ -265,19 +265,19 @@ cpdef inline int64_t cast_from_unit(object ts, object unit) except? -1:
265265
m = 1L
266266
p = 0
267267
else:
268-
raise ValueError("cannot cast unit {0}".format(unit))
268+
raise ValueError("cannot cast unit {unit}".format(unit=unit))
269269

270270
# just give me the unit back
271271
if ts is None:
272272
return m
273273

274274
# cast the unit, multiply base/frace separately
275275
# to avoid precision issues from float -> int
276-
base = <int64_t> ts
276+
base = <int64_t>ts
277277
frac = ts - base
278278
if p:
279279
frac = round(frac, p)
280-
return <int64_t> (base * m) + <int64_t> (frac * m)
280+
return <int64_t>(base * m) + <int64_t>(frac * m)
281281

282282

283283
cdef inline _decode_if_necessary(object ts):
@@ -288,19 +288,18 @@ cdef inline _decode_if_necessary(object ts):
288288
return ts
289289

290290

291-
cdef inline parse_timedelta_string(object ts, specified_unit=None):
291+
cdef inline parse_timedelta_string(object ts):
292292
"""
293293
Parse a regular format timedelta string. Return an int64_t (in ns)
294294
or raise a ValueError on an invalid parse.
295295
"""
296296

297297
cdef:
298298
unicode c
299-
bint neg=0, have_dot=0, have_value=0, have_hhmmss=0
300-
object current_unit=None
301-
object fallback_unit=None
302-
int64_t result=0, m=0, r
303-
list number=[], frac=[], unit=[]
299+
bint neg = 0, have_dot = 0, have_value = 0, have_hhmmss = 0
300+
object current_unit = None
301+
int64_t result = 0, m = 0, r
302+
list number = [], frac = [], unit = []
304303

305304
# neg : tracks if we have a leading negative for the value
306305
# have_dot : tracks if we are processing a dot (either post hhmmss or
@@ -375,7 +374,7 @@ cdef inline parse_timedelta_string(object ts, specified_unit=None):
375374
have_hhmmss = 1
376375
else:
377376
raise ValueError("expecting hh:mm:ss format, "
378-
"received: {0}".format(ts))
377+
"received: {ts}".format(ts=ts))
379378

380379
unit, number = [], []
381380

@@ -450,13 +449,9 @@ cdef inline parse_timedelta_string(object ts, specified_unit=None):
450449
if have_value:
451450
raise ValueError("have leftover units")
452451
if len(number):
453-
fallback_unit = 'ns' if specified_unit is None else specified_unit
454-
r = timedelta_from_spec(number, frac, fallback_unit)
452+
r = timedelta_from_spec(number, frac, 'ns')
455453
result += timedelta_as_neg(r, neg)
456454

457-
if (specified_unit is not None) and (fallback_unit is None):
458-
raise ValueError("unit was specified but is redundant/ambiguous")
459-
460455
return result
461456

462457

@@ -488,7 +483,7 @@ cdef inline timedelta_from_spec(object number, object frac, object unit):
488483
unit = ''.join(unit)
489484
unit = timedelta_abbrevs[unit.lower()]
490485
except KeyError:
491-
raise ValueError("invalid abbreviation: {0}".format(unit))
486+
raise ValueError("invalid abbreviation: {unit}".format(unit=unit))
492487

493488
n = ''.join(number) + '.' + ''.join(frac)
494489
return cast_from_unit(float(n), unit)
@@ -597,10 +592,10 @@ cdef inline int64_t parse_iso_format_string(object ts) except? -1:
597592
cdef:
598593
unicode c
599594
int64_t result = 0, r
600-
int p=0
595+
int p = 0
601596
object dec_unit = 'ms', err_msg
602-
bint have_dot=0, have_value=0, neg=0
603-
list number=[], unit=[]
597+
bint have_dot = 0, have_value = 0, neg = 0
598+
list number = [], unit = []
604599

605600
ts = _decode_if_necessary(ts)
606601

@@ -687,8 +682,8 @@ cdef _to_py_int_float(v):
687682
return int(v)
688683
elif is_float_object(v):
689684
return float(v)
690-
raise TypeError("Invalid type {0}. Must be int or "
691-
"float.".format(type(v)))
685+
raise TypeError("Invalid type {typ}. Must be int or "
686+
"float.".format(typ=type(v)))
692687

693688

694689
# Similar to Timestamp/datetime, this is a construction requirement for
@@ -734,9 +729,10 @@ cdef class _Timedelta(timedelta):
734729
return True
735730

736731
# only allow ==, != ops
737-
raise TypeError('Cannot compare type {!r} with type ' \
738-
'{!r}'.format(type(self).__name__,
739-
type(other).__name__))
732+
raise TypeError('Cannot compare type {cls} with '
733+
'type {other}'
734+
.format(cls=type(self).__name__,
735+
other=type(other).__name__))
740736
if util.is_array(other):
741737
return PyObject_RichCompare(np.array([self]), other, op)
742738
return PyObject_RichCompare(other, self, reverse_ops[op])
@@ -745,9 +741,9 @@ cdef class _Timedelta(timedelta):
745741
return False
746742
elif op == Py_NE:
747743
return True
748-
raise TypeError('Cannot compare type {!r} with type ' \
749-
'{!r}'.format(type(self).__name__,
750-
type(other).__name__))
744+
raise TypeError('Cannot compare type {cls} with type {other}'
745+
.format(cls=type(self).__name__,
746+
other=type(other).__name__))
751747

752748
return cmp_scalar(self.value, ots.value, op)
753749

@@ -985,8 +981,8 @@ cdef class _Timedelta(timedelta):
985981
sign = " "
986982

987983
if format == 'all':
988-
fmt = "{days} days{sign}{hours:02}:{minutes:02}:{seconds:02}." \
989-
"{milliseconds:03}{microseconds:03}{nanoseconds:03}"
984+
fmt = ("{days} days{sign}{hours:02}:{minutes:02}:{seconds:02}."
985+
"{milliseconds:03}{microseconds:03}{nanoseconds:03}")
990986
else:
991987
# if we have a partial day
992988
subs = (self._h or self._m or self._s or
@@ -1011,7 +1007,7 @@ cdef class _Timedelta(timedelta):
10111007
return fmt.format(**comp_dict)
10121008

10131009
def __repr__(self):
1014-
return "Timedelta('{0}')".format(self._repr_base(format='long'))
1010+
return "Timedelta('{val}')".format(val=self._repr_base(format='long'))
10151011

10161012
def __str__(self):
10171013
return self._repr_base(format='long')
@@ -1065,8 +1061,8 @@ cdef class _Timedelta(timedelta):
10651061
components.nanoseconds)
10661062
# Trim unnecessary 0s, 1.000000000 -> 1
10671063
seconds = seconds.rstrip('0').rstrip('.')
1068-
tpl = 'P{td.days}DT{td.hours}H{td.minutes}M{seconds}S'.format(
1069-
td=components, seconds=seconds)
1064+
tpl = ('P{td.days}DT{td.hours}H{td.minutes}M{seconds}S'
1065+
.format(td=components, seconds=seconds))
10701066
return tpl
10711067

10721068

@@ -1119,21 +1115,10 @@ class Timedelta(_Timedelta):
11191115
if isinstance(value, Timedelta):
11201116
value = value.value
11211117
elif is_string_object(value):
1122-
# Check if it is just a number in a string
1123-
try:
1124-
value = int(value)
1125-
except (ValueError, TypeError):
1126-
try:
1127-
value = float(value)
1128-
except (ValueError, TypeError):
1129-
pass
1130-
1131-
if is_integer_object(value) or is_float_object(value):
1132-
value = convert_to_timedelta64(value, unit)
1133-
elif len(value) > 0 and value[0] == 'P':
1118+
if len(value) > 0 and value[0] == 'P':
11341119
value = parse_iso_format_string(value)
11351120
else:
1136-
value = parse_timedelta_string(value, unit)
1121+
value = parse_timedelta_string(value)
11371122
value = np.timedelta64(value)
11381123
elif PyDelta_Check(value):
11391124
value = convert_to_timedelta64(value, 'ns')

0 commit comments

Comments
 (0)