diff --git a/doc/source/whatsnew/v1.2.0.rst b/doc/source/whatsnew/v1.2.0.rst index e2521cedb64cc..8625f94bf39c0 100644 --- a/doc/source/whatsnew/v1.2.0.rst +++ b/doc/source/whatsnew/v1.2.0.rst @@ -607,6 +607,7 @@ Datetimelike - Bug in :meth:`Series.isin` with ``datetime64[ns]`` dtype and :meth:`.DatetimeIndex.isin` failing to consider timezone-aware and timezone-naive datetimes as always different (:issue:`35728`) - Bug in :meth:`Series.isin` with ``PeriodDtype`` dtype and :meth:`PeriodIndex.isin` failing to consider arguments with different ``PeriodDtype`` as always different (:issue:`37528`) - Bug in :class:`Period` constructor now correctly handles nanoseconds in the ``value`` argument (:issue:`34621` and :issue:`17053`) +- Bug in :meth:`Timestamp.isoformat`, now handles the ``timespec`` argument from the base :class:``datetime`` class (:issue:`26131`) Timedelta ^^^^^^^^^ diff --git a/pandas/_libs/tslibs/timestamps.pyx b/pandas/_libs/tslibs/timestamps.pyx index 242eb89d1e723..9e0b9e3dd674a 100644 --- a/pandas/_libs/tslibs/timestamps.pyx +++ b/pandas/_libs/tslibs/timestamps.pyx @@ -609,8 +609,8 @@ cdef class _Timestamp(ABCTimestamp): # ----------------------------------------------------------------- # Rendering Methods - def isoformat(self, sep: str = "T") -> str: - base = super(_Timestamp, self).isoformat(sep=sep) + def isoformat(self, sep: str = "T", timespec: str = "auto") -> str: + base = super(_Timestamp, self).isoformat(sep=sep, timespec=timespec) if self.nanosecond == 0: return base @@ -619,7 +619,7 @@ cdef class _Timestamp(ABCTimestamp): else: base1, base2 = base, "" - if self.microsecond != 0: + if self.microsecond != 0 and timespec in ("auto", "microseconds"): base1 += f"{self.nanosecond:03d}" else: base1 += f".{self.nanosecond:09d}" diff --git a/pandas/tests/scalar/timestamp/test_formats.py b/pandas/tests/scalar/timestamp/test_formats.py new file mode 100644 index 0000000000000..e291df4a15e55 --- /dev/null +++ b/pandas/tests/scalar/timestamp/test_formats.py @@ -0,0 +1,9 @@ +from pandas import Timestamp + + +def test_isoformat(): + ts = Timestamp( + year=2019, month=5, day=18, hour=15, minute=17, second=8, microsecond=132263 + ) + assert ts.isoformat() == "2019-05-18T15:17:08.132263" + assert ts.isoformat(timespec="seconds") == "2019-05-18T15:17:08"