diff --git a/pandas/core/arrays/datetimelike.py b/pandas/core/arrays/datetimelike.py index c01b04991e52b..6b2ed2199703d 100644 --- a/pandas/core/arrays/datetimelike.py +++ b/pandas/core/arrays/datetimelike.py @@ -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, @@ -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): @@ -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 diff --git a/pandas/core/arrays/datetimes.py b/pandas/core/arrays/datetimes.py index c197d6d6e634b..59e9fe49f650a 100644 --- a/pandas/core/arrays/datetimes.py +++ b/pandas/core/arrays/datetimes.py @@ -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 diff --git a/pandas/core/arrays/period.py b/pandas/core/arrays/period.py index 60febc5f5636d..6fd98bb25380a 100644 --- a/pandas/core/arrays/period.py +++ b/pandas/core/arrays/period.py @@ -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. @@ -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): """ @@ -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): """ diff --git a/pandas/core/arrays/timedeltas.py b/pandas/core/arrays/timedeltas.py index a5d074df338ee..314a3948f1032 100644 --- a/pandas/core/arrays/timedeltas.py +++ b/pandas/core/arrays/timedeltas.py @@ -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