Skip to content

Commit 9b24770

Browse files
jbrockmendeljreback
authored andcommitted
Implement tslibs.__init__, move easy bits of tslib (#21738)
1 parent 1c5b342 commit 9b24770

File tree

8 files changed

+82
-63
lines changed

8 files changed

+82
-63
lines changed

pandas/_libs/tslib.pyx

+2-53
Original file line numberDiff line numberDiff line change
@@ -35,18 +35,17 @@ from cython cimport Py_ssize_t
3535

3636

3737
import pytz
38-
UTC = pytz.utc
3938

4039

4140
from tslibs.timedeltas cimport cast_from_unit
42-
from tslibs.timedeltas import Timedelta
41+
from tslibs.timedeltas import Timedelta, ints_to_pytimedelta # noqa:F841
4342
from tslibs.timezones cimport (is_utc, is_tzlocal, is_fixed_offset,
4443
treat_tz_as_pytz, get_dst_info)
4544
from tslibs.conversion cimport (tz_convert_single, _TSObject,
4645
convert_datetime_to_tsobject,
4746
get_datetime64_nanos,
4847
tz_convert_utc_to_tzlocal)
49-
from tslibs.conversion import tz_convert_single
48+
from tslibs.conversion import tz_convert_single, normalize_date # noqa:F841
5049

5150
from tslibs.nattype import NaT, nat_strings, iNaT
5251
from tslibs.nattype cimport checknull_with_nat, NPY_NAT
@@ -185,29 +184,6 @@ def ints_to_pydatetime(ndarray[int64_t] arr, tz=None, freq=None,
185184
return result
186185

187186

188-
def ints_to_pytimedelta(ndarray[int64_t] arr, box=False):
189-
# convert an i8 repr to an ndarray of timedelta or Timedelta (if box ==
190-
# True)
191-
192-
cdef:
193-
Py_ssize_t i, n = len(arr)
194-
int64_t value
195-
ndarray[object] result = np.empty(n, dtype=object)
196-
197-
for i in range(n):
198-
199-
value = arr[i]
200-
if value == NPY_NAT:
201-
result[i] = NaT
202-
else:
203-
if box:
204-
result[i] = Timedelta(value)
205-
else:
206-
result[i] = timedelta(microseconds=int(value) / 1000)
207-
208-
return result
209-
210-
211187
def _test_parse_iso8601(object ts):
212188
"""
213189
TESTING ONLY: Parse string into Timestamp using iso8601 parser. Used
@@ -740,30 +716,3 @@ cdef inline bint _parse_today_now(str val, int64_t* iresult):
740716
iresult[0] = Timestamp.today().value
741717
return True
742718
return False
743-
744-
# ----------------------------------------------------------------------
745-
# Some general helper functions
746-
747-
748-
cpdef normalize_date(object dt):
749-
"""
750-
Normalize datetime.datetime value to midnight. Returns datetime.date as a
751-
datetime.datetime at midnight
752-
753-
Returns
754-
-------
755-
normalized : datetime.datetime or Timestamp
756-
"""
757-
if PyDateTime_Check(dt):
758-
if not PyDateTime_CheckExact(dt):
759-
# i.e. a Timestamp object
760-
return dt.replace(hour=0, minute=0, second=0, microsecond=0,
761-
nanosecond=0)
762-
else:
763-
# regular datetime object
764-
return dt.replace(hour=0, minute=0, second=0, microsecond=0)
765-
# TODO: Make sure DST crossing is handled correctly here
766-
elif PyDate_Check(dt):
767-
return datetime(dt.year, dt.month, dt.day)
768-
else:
769-
raise TypeError('Unrecognized type: %s' % type(dt))

pandas/_libs/tslibs/__init__.py

+7-1
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,8 @@
11
# -*- coding: utf-8 -*-
2-
# cython: profile=False
2+
# flake8: noqa
3+
4+
from .conversion import normalize_date, localize_pydatetime, tz_convert_single
5+
from .nattype import NaT, iNaT
6+
from .np_datetime import OutOfBoundsDatetime
7+
from .timestamps import Timestamp
8+
from .timedeltas import delta_to_nanoseconds, ints_to_pytimedelta, Timedelta

pandas/_libs/tslibs/conversion.pyx

+29
Original file line numberDiff line numberDiff line change
@@ -1025,6 +1025,35 @@ cdef inline str _render_tstamp(int64_t val):
10251025
# ----------------------------------------------------------------------
10261026
# Normalization
10271027

1028+
1029+
def normalize_date(object dt):
1030+
"""
1031+
Normalize datetime.datetime value to midnight. Returns datetime.date as a
1032+
datetime.datetime at midnight
1033+
1034+
Parameters
1035+
----------
1036+
dt : date, datetime, or Timestamp
1037+
1038+
Returns
1039+
-------
1040+
normalized : datetime.datetime or Timestamp
1041+
"""
1042+
if PyDateTime_Check(dt):
1043+
if not PyDateTime_CheckExact(dt):
1044+
# i.e. a Timestamp object
1045+
return dt.replace(hour=0, minute=0, second=0, microsecond=0,
1046+
nanosecond=0)
1047+
else:
1048+
# regular datetime object
1049+
return dt.replace(hour=0, minute=0, second=0, microsecond=0)
1050+
# TODO: Make sure DST crossing is handled correctly here
1051+
elif PyDate_Check(dt):
1052+
return datetime(dt.year, dt.month, dt.day)
1053+
else:
1054+
raise TypeError('Unrecognized type: %s' % type(dt))
1055+
1056+
10281057
@cython.wraparound(False)
10291058
@cython.boundscheck(False)
10301059
def date_normalize(ndarray[int64_t] stamps, tz=None):

pandas/_libs/tslibs/timedeltas.pyx

+38
Original file line numberDiff line numberDiff line change
@@ -79,6 +79,44 @@ cdef dict timedelta_abbrevs = { 'D': 'd',
7979

8080
_no_input = object()
8181

82+
83+
# ----------------------------------------------------------------------
84+
# API
85+
86+
def ints_to_pytimedelta(ndarray[int64_t] arr, box=False):
87+
"""
88+
convert an i8 repr to an ndarray of timedelta or Timedelta (if box ==
89+
True)
90+
91+
Parameters
92+
----------
93+
arr : ndarray[int64_t]
94+
box : bool, default False
95+
96+
Returns
97+
-------
98+
result : ndarray[object]
99+
array of Timedelta or timedeltas objects
100+
"""
101+
cdef:
102+
Py_ssize_t i, n = len(arr)
103+
int64_t value
104+
ndarray[object] result = np.empty(n, dtype=object)
105+
106+
for i in range(n):
107+
108+
value = arr[i]
109+
if value == NPY_NAT:
110+
result[i] = NaT
111+
else:
112+
if box:
113+
result[i] = Timedelta(value)
114+
else:
115+
result[i] = timedelta(microseconds=int(value) / 1000)
116+
117+
return result
118+
119+
82120
# ----------------------------------------------------------------------
83121

84122
cpdef int64_t delta_to_nanoseconds(delta) except? -1:

pandas/_libs/tslibs/timestamps.pyx

-1
Original file line numberDiff line numberDiff line change
@@ -645,7 +645,6 @@ class Timestamp(_Timestamp):
645645
return NaT
646646

647647
if is_string_object(freq):
648-
from pandas.tseries.frequencies import to_offset
649648
freq = to_offset(freq)
650649

651650
return create_timestamp_from_ts(ts.value, ts.dts, ts.tzinfo, freq)

pandas/core/generic.py

-2
Original file line numberDiff line numberDiff line change
@@ -7156,7 +7156,6 @@ def first(self, offset):
71567156
at_time : Select values at a particular time of the day
71577157
between_time : Select values between particular times of the day
71587158
"""
7159-
from pandas.tseries.frequencies import to_offset
71607159
if not isinstance(self.index, DatetimeIndex):
71617160
raise TypeError("'first' only supports a DatetimeIndex index")
71627161

@@ -7220,7 +7219,6 @@ def last(self, offset):
72207219
at_time : Select values at a particular time of the day
72217220
between_time : Select values between particular times of the day
72227221
"""
7223-
from pandas.tseries.frequencies import to_offset
72247222
if not isinstance(self.index, DatetimeIndex):
72257223
raise TypeError("'last' only supports a DatetimeIndex index")
72267224

pandas/tests/tseries/offsets/test_offsets.py

+1-6
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,7 @@
3333
import pandas.tseries.offsets as offsets
3434
from pandas.io.pickle import read_pickle
3535
from pandas._libs.tslibs import timezones
36-
from pandas._libs.tslib import normalize_date, NaT, Timestamp
36+
from pandas._libs.tslib import NaT, Timestamp
3737
import pandas._libs.tslib as tslib
3838
import pandas.util.testing as tm
3939
from pandas.tseries.holiday import USFederalHolidayCalendar
@@ -59,11 +59,6 @@ def test_ole2datetime():
5959
ole2datetime(60)
6060

6161

62-
def test_normalize_date():
63-
actual = normalize_date(datetime(2007, 10, 1, 1, 12, 5, 10))
64-
assert actual == datetime(2007, 10, 1)
65-
66-
6762
def test_to_m8():
6863
valb = datetime(2007, 10, 1)
6964
valu = _to_m8(valb)

pandas/tests/tslibs/test_tslib.py

+5
Original file line numberDiff line numberDiff line change
@@ -16,3 +16,8 @@ def test_normalize_date():
1616

1717
result = tslib.normalize_date(value)
1818
assert (result == datetime(2012, 9, 7))
19+
20+
value = datetime(2007, 10, 1, 1, 12, 5, 10)
21+
22+
actual = tslib.normalize_date(value)
23+
assert actual == datetime(2007, 10, 1)

0 commit comments

Comments
 (0)