Skip to content

Commit

Permalink
Rendering Methods portions of pandas-dev#24024 (pandas-dev#24392)
Browse files Browse the repository at this point in the history
  • Loading branch information
jbrockmendel authored and Pingviinituutti committed Feb 28, 2019
1 parent 60d1166 commit 2a28e53
Show file tree
Hide file tree
Showing 4 changed files with 80 additions and 40 deletions.
88 changes: 53 additions & 35 deletions pandas/core/arrays/datetimelike.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
import pandas.compat as compat
from pandas.errors import (
AbstractMethodError, NullFrequencyError, PerformanceWarning)
from pandas.util._decorators import Appender, deprecate_kwarg
from pandas.util._decorators import Appender, Substitution, deprecate_kwarg

from pandas.core.dtypes.common import (
is_bool_dtype, is_datetime64_any_dtype, is_datetime64_dtype,
Expand Down Expand Up @@ -86,44 +86,45 @@ class DatelikeOps(object):
Common ops for DatetimeIndex/PeriodIndex, but not TimedeltaIndex.
"""

@Substitution(URL="https://docs.python.org/3/library/datetime.html"
"#strftime-and-strptime-behavior")
def strftime(self, date_format):
from pandas import Index
return Index(self.format(date_format=date_format),
dtype=compat.text_type)
strftime.__doc__ = """
Convert to Index using specified date_format.
"""
Convert to Index using specified date_format.
Return an Index of formatted strings specified by date_format, which
supports the same string format as the python standard library. Details
of the string format can be found in `python string format doc <{0}>`__
Return an Index of formatted strings specified by date_format, which
supports the same string format as the python standard library. Details
of the string format can be found in `python string format
doc <%(URL)s>`__
Parameters
----------
date_format : str
Date format string (e.g. "%Y-%m-%d").
Parameters
----------
date_format : str
Date format string (e.g. "%%Y-%%m-%%d").
Returns
-------
Index
Index of formatted strings
See Also
--------
to_datetime : Convert the given argument to datetime.
DatetimeIndex.normalize : Return DatetimeIndex with times to midnight.
DatetimeIndex.round : Round the DatetimeIndex to the specified freq.
DatetimeIndex.floor : Floor the DatetimeIndex to the specified freq.
Examples
--------
>>> rng = pd.date_range(pd.Timestamp("2018-03-10 09:00"),
... periods=3, freq='s')
>>> rng.strftime('%B %d, %Y, %r')
Index(['March 10, 2018, 09:00:00 AM', 'March 10, 2018, 09:00:01 AM',
'March 10, 2018, 09:00:02 AM'],
dtype='object')
""".format("https://docs.python.org/3/library/datetime.html"
"#strftime-and-strptime-behavior")
Returns
-------
Index
Index of formatted strings
See Also
--------
to_datetime : Convert the given argument to datetime.
DatetimeIndex.normalize : Return DatetimeIndex with times to midnight.
DatetimeIndex.round : Round the DatetimeIndex to the specified freq.
DatetimeIndex.floor : Floor the DatetimeIndex to the specified freq.
Examples
--------
>>> rng = pd.date_range(pd.Timestamp("2018-03-10 09:00"),
... periods=3, freq='s')
>>> rng.strftime('%%B %%d, %%Y, %%r')
Index(['March 10, 2018, 09:00:00 AM', 'March 10, 2018, 09:00:01 AM',
'March 10, 2018, 09:00:02 AM'],
dtype='object')
"""
from pandas import Index
return Index(self._format_native_types(date_format=date_format))


class TimelikeOps(object):
Expand Down Expand Up @@ -298,6 +299,23 @@ def asi8(self):
# do not cache or you'll create a memory leak
return self._data.view('i8')

# ----------------------------------------------------------------
# Rendering Methods

def _format_native_types(self, na_rep=u'NaT', date_format=None):
"""
Helper method for astype when converting to strings.
Returns
-------
ndarray[str]
"""
raise AbstractMethodError(self)

def _formatter(self, boxed=False):
# TODO: Remove Datetime & DatetimeTZ formatters.
return "'{}'".format

# ----------------------------------------------------------------
# Array-Like / EA-Interface Methods

Expand Down
12 changes: 12 additions & 0 deletions pandas/core/arrays/datetimes.py
Original file line number Diff line number Diff line change
Expand Up @@ -468,6 +468,18 @@ def _validate_fill_value(self, fill_value):
"Got '{got}'.".format(got=fill_value))
return fill_value

# -----------------------------------------------------------------
# Rendering Methods

def _format_native_types(self, na_rep=u'NaT', date_format=None, **kwargs):
from pandas.io.formats.format import _get_format_datetime64_from_values
fmt = _get_format_datetime64_from_values(self, date_format)

return tslib.format_array_from_datetime(self.asi8,
tz=self.tz,
format=fmt,
na_rep=na_rep)

# -----------------------------------------------------------------
# Comparison Methods

Expand Down
10 changes: 5 additions & 5 deletions pandas/core/arrays/period.py
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,9 @@ def wrapper(self, other):
return compat.set_function_name(wrapper, opname, cls)


class PeriodArray(dtl.DatetimeLikeArrayMixin, ExtensionArray):
class PeriodArray(dtl.DatetimeLikeArrayMixin,
dtl.DatelikeOps,
ExtensionArray):
"""
Pandas ExtensionArray for storing Period data.
Expand Down Expand Up @@ -565,7 +567,7 @@ def asfreq(self, freq=None, how='E'):
return type(self)(new_data, freq=freq)

# ------------------------------------------------------------------
# Formatting
# Rendering Methods

def _format_native_types(self, na_rep=u'NaT', date_format=None, **kwargs):
"""
Expand All @@ -589,9 +591,7 @@ def _format_native_types(self, na_rep=u'NaT', date_format=None, **kwargs):
values = np.array([formatter(dt) for dt in values])
return values

# Delegation...
def strftime(self, date_format):
return self._format_native_types(date_format=date_format)
# ------------------------------------------------------------------

def repeat(self, repeats, *args, **kwargs):
"""
Expand Down
10 changes: 10 additions & 0 deletions pandas/core/arrays/timedeltas.py
Original file line number Diff line number Diff line change
Expand Up @@ -231,6 +231,16 @@ def _validate_fill_value(self, fill_value):
"Got '{got}'.".format(got=fill_value))
return fill_value

# ----------------------------------------------------------------
# Rendering Methods

def _formatter(self, boxed=False):
from pandas.io.formats.format import _get_format_timedelta64
return _get_format_timedelta64(self, box=True)

def _format_native_types(self):
return self.astype(object)

# ----------------------------------------------------------------
# Arithmetic Methods

Expand Down

0 comments on commit 2a28e53

Please sign in to comment.