diff --git a/python/pyarrow/scalar.pxi b/python/pyarrow/scalar.pxi index f438c8847bb..3d971db7d14 100644 --- a/python/pyarrow/scalar.pxi +++ b/python/pyarrow/scalar.pxi @@ -522,6 +522,23 @@ cdef class TimestampScalar(Scalar): return _datetime_from_int(sp.value, unit=dtype.unit(), tzinfo=tzinfo) + def __repr__(self): + """ + Return the representation of TimestampScalar using `strftime` to avoid + original repr datetime values being out of range. + """ + cdef: + CTimestampScalar* sp = self.wrapped.get() + CTimestampType* dtype = sp.type.get() + + if not dtype.timezone().empty(): + type_format = str(_pc().strftime(self, format="%Y-%m-%dT%H:%M:%S%z")) + else: + type_format = str(_pc().strftime(self)) + return ''.format( + self.__class__.__name__, type_format + ) + cdef class DurationScalar(Scalar): """ diff --git a/python/pyarrow/tests/test_convert_builtin.py b/python/pyarrow/tests/test_convert_builtin.py index af4c91a8945..cf2535a3c62 100644 --- a/python/pyarrow/tests/test_convert_builtin.py +++ b/python/pyarrow/tests/test_convert_builtin.py @@ -1353,7 +1353,7 @@ def test_sequence_timestamp_from_int_with_unit(): assert len(arr_s) == 1 assert arr_s.type == s assert repr(arr_s[0]) == ( - "" + "" ) assert str(arr_s[0]) == "1970-01-01 00:00:01" diff --git a/python/pyarrow/tests/test_scalars.py b/python/pyarrow/tests/test_scalars.py index b7180e5250f..e08a71e3a26 100644 --- a/python/pyarrow/tests/test_scalars.py +++ b/python/pyarrow/tests/test_scalars.py @@ -154,6 +154,18 @@ def test_hashing_struct_scalar(): assert hash1 == hash2 +def test_timestamp_scalar(): + a = repr(pa.scalar("0000-01-01").cast(pa.timestamp("s"))) + assert a == "" + b = repr(pa.scalar(datetime.datetime(2015, 1, 1), type=pa.timestamp('s', tz='UTC'))) + assert b == "" + c = repr(pa.scalar(datetime.datetime(2015, 1, 1), type=pa.timestamp('us'))) + assert c == "" + d = repr(pc.assume_timezone( + pa.scalar("2000-01-01").cast(pa.timestamp("s")), "America/New_York")) + assert d == "" + + def test_bool(): false = pa.scalar(False) true = pa.scalar(True) diff --git a/python/pyarrow/types.pxi b/python/pyarrow/types.pxi index fbd4f8a94b6..12ad2fc4b6f 100644 --- a/python/pyarrow/types.pxi +++ b/python/pyarrow/types.pxi @@ -3605,9 +3605,9 @@ def timestamp(unit, tz=None): >>> from datetime import datetime >>> pa.scalar(datetime(2012, 1, 1), type=pa.timestamp('s', tz='UTC')) - )> + >>> pa.scalar(datetime(2012, 1, 1), type=pa.timestamp('us')) - + Returns -------