From 7fabb957f367b00f6d277d11581510eccb95d431 Mon Sep 17 00:00:00 2001 From: Brock Mendel Date: Thu, 20 Dec 2018 19:18:57 -0800 Subject: [PATCH 1/3] rendering methods portion of #24024 --- pandas/core/arrays/datetimelike.py | 20 ++++++++++++++++++-- pandas/core/arrays/datetimes.py | 12 ++++++++++++ pandas/core/arrays/period.py | 10 +++++----- pandas/core/arrays/timedeltas.py | 10 ++++++++++ 4 files changed, 45 insertions(+), 7 deletions(-) diff --git a/pandas/core/arrays/datetimelike.py b/pandas/core/arrays/datetimelike.py index 6d8e41900ce2d..b604332bae0bd 100644 --- a/pandas/core/arrays/datetimelike.py +++ b/pandas/core/arrays/datetimelike.py @@ -88,8 +88,7 @@ class DatelikeOps(object): def strftime(self, date_format): from pandas import Index - return Index(self.format(date_format=date_format), - dtype=compat.text_type) + return Index(self._format_native_types(date_format=date_format)) strftime.__doc__ = """ Convert to Index using specified date_format. @@ -298,6 +297,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 From 431a90c9cb4353962ebfaf5c99c9989d70bfb495 Mon Sep 17 00:00:00 2001 From: Brock Mendel Date: Fri, 21 Dec 2018 16:19:31 -0800 Subject: [PATCH 2/3] prettify docstring --- pandas/core/arrays/datetimelike.py | 70 +++++++++++++++--------------- 1 file changed, 36 insertions(+), 34 deletions(-) diff --git a/pandas/core/arrays/datetimelike.py b/pandas/core/arrays/datetimelike.py index 72e0fb5eb3ada..5b544e96743be 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,43 +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_native_types(date_format=date_format)) - 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}>`__ - 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): From b355220dad4d2550a8de85a2d5dbb6d50d0a47b2 Mon Sep 17 00:00:00 2001 From: Brock Mendel Date: Fri, 21 Dec 2018 17:13:35 -0800 Subject: [PATCH 3/3] adapt to older string formatting --- pandas/core/arrays/datetimelike.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/pandas/core/arrays/datetimelike.py b/pandas/core/arrays/datetimelike.py index 5b544e96743be..6b2ed2199703d 100644 --- a/pandas/core/arrays/datetimelike.py +++ b/pandas/core/arrays/datetimelike.py @@ -95,12 +95,12 @@ def strftime(self, 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 <{URL}>`__ + doc <%(URL)s>`__ Parameters ---------- date_format : str - Date format string (e.g. "%Y-%m-%d"). + Date format string (e.g. "%%Y-%%m-%%d"). Returns ------- @@ -118,7 +118,7 @@ def strftime(self, date_format): -------- >>> rng = pd.date_range(pd.Timestamp("2018-03-10 09:00"), ... periods=3, freq='s') - >>> rng.strftime('%B %d, %Y, %r') + >>> 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')