From 05c392ed4cacfc3c9b07f5cd0737527c873a4354 Mon Sep 17 00:00:00 2001 From: Joris Van den Bossche Date: Wed, 20 Mar 2024 11:01:27 +0100 Subject: [PATCH 01/18] GH-29828: [Python] Support month and day-time interval types --- docs/source/python/api/arrays.rst | 4 +++ docs/source/python/api/datatypes.rst | 2 ++ python/pyarrow/__init__.py | 4 ++- python/pyarrow/array.pxi | 14 +++++++++ python/pyarrow/includes/libarrow.pxd | 2 ++ python/pyarrow/lib.pxd | 8 +++++ python/pyarrow/lib.pyx | 2 ++ python/pyarrow/scalar.pxi | 36 ++++++++++++++++++++++ python/pyarrow/src/arrow/python/helpers.cc | 2 ++ python/pyarrow/tests/test_compute.py | 25 +++++++++++++++ python/pyarrow/tests/test_misc.py | 6 ++++ python/pyarrow/tests/test_types.py | 6 +++- python/pyarrow/types.pxi | 14 +++++++++ python/pyarrow/types.py | 5 +-- 14 files changed, 126 insertions(+), 4 deletions(-) diff --git a/docs/source/python/api/arrays.rst b/docs/source/python/api/arrays.rst index 290ce09befb1..66adfa6addd7 100644 --- a/docs/source/python/api/arrays.rst +++ b/docs/source/python/api/arrays.rst @@ -80,6 +80,8 @@ may expose data type-specific methods or properties. Date64Array TimestampArray DurationArray + MonthIntervalArray + DayTimeIntervalArray MonthDayNanoIntervalArray Decimal32Array Decimal64Array @@ -148,6 +150,8 @@ classes may expose data type-specific methods or properties. Date64Scalar TimestampScalar DurationScalar + MonthIntervalScalar + DayTimeIntervalScalar MonthDayNanoIntervalScalar Decimal32Scalar Decimal64Scalar diff --git a/docs/source/python/api/datatypes.rst b/docs/source/python/api/datatypes.rst index ea9e547d32c7..5121da5667d4 100644 --- a/docs/source/python/api/datatypes.rst +++ b/docs/source/python/api/datatypes.rst @@ -48,6 +48,8 @@ These should be used to create Arrow data types and schemas. date32 date64 duration + month_interval + day_time_interval month_day_nano_interval binary string diff --git a/python/pyarrow/__init__.py b/python/pyarrow/__init__.py index c024cdc69a7d..b0fb74c819b3 100644 --- a/python/pyarrow/__init__.py +++ b/python/pyarrow/__init__.py @@ -169,7 +169,7 @@ def print_entry(label, value): int8, int16, int32, int64, uint8, uint16, uint32, uint64, time32, time64, timestamp, date32, date64, duration, - month_day_nano_interval, + month_interval, day_time_interval, month_day_nano_interval, float16, float32, float64, binary, string, utf8, binary_view, string_view, large_binary, large_string, large_utf8, @@ -224,6 +224,7 @@ def print_entry(label, value): DictionaryArray, Date32Array, Date64Array, TimestampArray, Time32Array, Time64Array, DurationArray, + MonthIntervalArray, DayTimeIntervalArray, MonthDayNanoIntervalArray, Decimal32Array, Decimal64Array, Decimal128Array, Decimal256Array, StructArray, ExtensionArray, @@ -240,6 +241,7 @@ def print_entry(label, value): Date32Scalar, Date64Scalar, Time32Scalar, Time64Scalar, TimestampScalar, DurationScalar, + MonthIntervalScalar, DayTimeIntervalScalar, MonthDayNanoIntervalScalar, BinaryScalar, LargeBinaryScalar, BinaryViewScalar, StringScalar, LargeStringScalar, StringViewScalar, diff --git a/python/pyarrow/array.pxi b/python/pyarrow/array.pxi index d45c3470f8c7..6e34a91019f4 100644 --- a/python/pyarrow/array.pxi +++ b/python/pyarrow/array.pxi @@ -2717,6 +2717,18 @@ cdef class DurationArray(NumericArray): """ +cdef class MonthIntervalArray(Array): + """ + Concrete class for Arrow arrays of interval[month] data type. + """ + + +cdef class DayTimeIntervalArray(Array): + """ + Concrete class for Arrow arrays of interval[day_time] data type. + """ + + cdef class MonthDayNanoIntervalArray(Array): """ Concrete class for Arrow arrays of interval[MonthDayNano] type. @@ -5316,6 +5328,8 @@ cdef dict _array_classes = { _Type_TIME32: Time32Array, _Type_TIME64: Time64Array, _Type_DURATION: DurationArray, + _Type_INTERVAL_MONTHS: MonthIntervalArray, + _Type_INTERVAL_DAY_TIME: DayTimeIntervalArray, _Type_INTERVAL_MONTH_DAY_NANO: MonthDayNanoIntervalArray, _Type_HALF_FLOAT: HalfFloatArray, _Type_FLOAT: FloatArray, diff --git a/python/pyarrow/includes/libarrow.pxd b/python/pyarrow/includes/libarrow.pxd index 25a9aa8da6f5..2b7353133735 100644 --- a/python/pyarrow/includes/libarrow.pxd +++ b/python/pyarrow/includes/libarrow.pxd @@ -146,6 +146,8 @@ cdef extern from "arrow/api.h" namespace "arrow" nogil: _Type_TIME32" arrow::Type::TIME32" _Type_TIME64" arrow::Type::TIME64" _Type_DURATION" arrow::Type::DURATION" + _Type_INTERVAL_MONTHS" arrow::Type::INTERVAL_MONTHS" + _Type_INTERVAL_DAY_TIME" arrow::Type::INTERVAL_DAY_TIME" _Type_INTERVAL_MONTH_DAY_NANO" arrow::Type::INTERVAL_MONTH_DAY_NANO" _Type_INTERVAL_DAY_TIME" arrow::Type::INTERVAL_DAY_TIME" _Type_INTERVAL_MONTHS" arrow::Type::INTERVAL_MONTHS" diff --git a/python/pyarrow/lib.pxd b/python/pyarrow/lib.pxd index 38f1ac69a807..013585139c30 100644 --- a/python/pyarrow/lib.pxd +++ b/python/pyarrow/lib.pxd @@ -503,6 +503,14 @@ cdef class ExtensionArray(Array): pass +cdef class MonthIntervalArray(Array): + pass + + +cdef class DayTimeIntervalArray(Array): + pass + + cdef class MonthDayNanoIntervalArray(Array): pass diff --git a/python/pyarrow/lib.pyx b/python/pyarrow/lib.pyx index d949720ca8e5..8ad18e5ab79b 100644 --- a/python/pyarrow/lib.pyx +++ b/python/pyarrow/lib.pyx @@ -130,6 +130,8 @@ Type_TIMESTAMP = _Type_TIMESTAMP Type_TIME32 = _Type_TIME32 Type_TIME64 = _Type_TIME64 Type_DURATION = _Type_DURATION +Type_INTERVAL_MONTHS = _Type_INTERVAL_MONTHS +Type_INTERVAL_DAY_TIME = _Type_INTERVAL_DAY_TIME Type_INTERVAL_MONTH_DAY_NANO = _Type_INTERVAL_MONTH_DAY_NANO Type_BINARY = _Type_BINARY Type_STRING = _Type_STRING diff --git a/python/pyarrow/scalar.pxi b/python/pyarrow/scalar.pxi index 8c9adf9b522c..2427ce3ed744 100644 --- a/python/pyarrow/scalar.pxi +++ b/python/pyarrow/scalar.pxi @@ -904,6 +904,40 @@ cdef class DurationScalar(Scalar): return datetime.timedelta(microseconds=sp.value // 1000) +cdef class MonthIntervalScalar(Scalar): + """ + Concrete class for month interval scalars. + """ + + def __repr__(self): + return ''.format( + self.__class__.__name__, frombytes(self.wrapped.get().ToString()) + ) + + def __str__(self): + return frombytes(self.wrapped.get().ToString()) + + def as_py(self): + raise NotImplementedError() + + +cdef class DayTimeIntervalScalar(Scalar): + """ + Concrete class for day-time interval scalars. + """ + + def __repr__(self): + return ''.format( + self.__class__.__name__, frombytes(self.wrapped.get().ToString()) + ) + + def __str__(self): + return frombytes(self.wrapped.get().ToString()) + + def as_py(self): + raise NotImplementedError() + + cdef class MonthDayNanoIntervalScalar(Scalar): """ Concrete class for month, day, nanosecond interval scalars. @@ -1681,6 +1715,8 @@ cdef dict _scalar_classes = { _Type_RUN_END_ENCODED: RunEndEncodedScalar, _Type_SPARSE_UNION: UnionScalar, _Type_DENSE_UNION: UnionScalar, + _Type_INTERVAL_MONTHS: MonthIntervalScalar, + _Type_INTERVAL_DAY_TIME: DayTimeIntervalScalar, _Type_INTERVAL_MONTH_DAY_NANO: MonthDayNanoIntervalScalar, _Type_EXTENSION: ExtensionScalar, } diff --git a/python/pyarrow/src/arrow/python/helpers.cc b/python/pyarrow/src/arrow/python/helpers.cc index 3b895001f928..16391e049964 100644 --- a/python/pyarrow/src/arrow/python/helpers.cc +++ b/python/pyarrow/src/arrow/python/helpers.cc @@ -69,6 +69,8 @@ std::shared_ptr GetPrimitiveType(Type::type type) { GET_PRIMITIVE_TYPE(LARGE_STRING, large_utf8); GET_PRIMITIVE_TYPE(BINARY_VIEW, binary_view); GET_PRIMITIVE_TYPE(STRING_VIEW, utf8_view); + GET_PRIMITIVE_TYPE(INTERVAL_MONTHS, month_interval); + GET_PRIMITIVE_TYPE(INTERVAL_DAY_TIME, day_time_interval); GET_PRIMITIVE_TYPE(INTERVAL_MONTH_DAY_NANO, month_day_nano_interval); default: return nullptr; diff --git a/python/pyarrow/tests/test_compute.py b/python/pyarrow/tests/test_compute.py index 0e0260808d6d..a13101dc5868 100644 --- a/python/pyarrow/tests/test_compute.py +++ b/python/pyarrow/tests/test_compute.py @@ -4631,3 +4631,28 @@ def test_winsorize(): result = pc.winsorize( arr, options=pc.WinsorizeOptions(lower_limit=0.1, upper_limit=0.8)) assert result.to_pylist() == [8, 4, 8, 8, 5, 3, 7, 2, 2, 6] + + +def test_interval_between(): + arr1 = pa.array( + [datetime.datetime(2020, 1, 1), None, datetime.datetime(1900, 12, 13)], + type=pa.timestamp('s') + ) + arr2 = pa.array( + [datetime.datetime(2020, 5, 5), datetime.datetime(2020, 10, 1), + datetime.datetime(2020, 1, 1)], + type=pa.timestamp('s') + ) + result = pc.month_day_nano_interval_between(arr1, arr2) + assert isinstance(result, pa.MonthDayNanoIntervalArray) + assert isinstance(result[0], pa.MonthDayNanoIntervalScalar) + + result = pc.month_interval_between(arr1, arr2) + assert isinstance(result, pa.MonthIntervalArray) + assert isinstance(result[0], pa.MonthIntervalScalar) + assert str(result[0]) == "4M" + + result = pc.day_time_interval_between(arr1, arr2) + assert isinstance(result, pa.DayTimeIntervalArray) + assert isinstance(result[0], pa.DayTimeIntervalScalar) + assert str(result[0]) == "125d0ms" diff --git a/python/pyarrow/tests/test_misc.py b/python/pyarrow/tests/test_misc.py index c0fa484e35ea..1a47f30a5e0c 100644 --- a/python/pyarrow/tests/test_misc.py +++ b/python/pyarrow/tests/test_misc.py @@ -227,6 +227,9 @@ def test_set_timezone_db_path_non_windows(): pa.Time32Array, pa.Time64Array, pa.DurationArray, + pa.MonthIntervalArray, + pa.DayTimeIntervalArray, + pa.MonthDayNanoIntervalArray, pa.Decimal128Array, pa.Decimal256Array, pa.StructArray, @@ -252,6 +255,9 @@ def test_set_timezone_db_path_non_windows(): pa.Time64Scalar, pa.TimestampScalar, pa.DurationScalar, + pa.MonthIntervalScalar, + pa.DayTimeIntervalScalar, + pa.MonthDayNanoIntervalScalar, pa.StringScalar, pa.BinaryScalar, pa.FixedSizeBinaryScalar, diff --git a/python/pyarrow/tests/test_types.py b/python/pyarrow/tests/test_types.py index 064eeb6e7a0e..aac4f1522779 100644 --- a/python/pyarrow/tests/test_types.py +++ b/python/pyarrow/tests/test_types.py @@ -55,6 +55,9 @@ def get_many_types(): pa.timestamp('us', tz='UTC'), pa.timestamp('us', tz='Europe/Paris'), pa.duration('s'), + pa.month_interval(), + pa.day_time_interval(), + pa.month_day_nano_interval(), pa.float16(), pa.float32(), pa.float64(), @@ -301,7 +304,8 @@ def test_is_temporal_date_time_timestamp(): time_types = [pa.time32('s'), pa.time64('ns')] timestamp_types = [pa.timestamp('ms')] duration_types = [pa.duration('ms')] - interval_types = [pa.month_day_nano_interval()] + interval_types = [pa.month_interval(), pa.day_time_interval(), + pa.month_day_nano_interval()] for case in (date_types + time_types + timestamp_types + duration_types + interval_types): diff --git a/python/pyarrow/types.pxi b/python/pyarrow/types.pxi index b6d647ce3db7..f6ee4089d03b 100644 --- a/python/pyarrow/types.pxi +++ b/python/pyarrow/types.pxi @@ -4350,6 +4350,18 @@ def duration(unit): return out +def month_interval(): + """ + """ + return primitive_type(_Type_INTERVAL_MONTHS) + + +def day_time_interval(): + """ + """ + return primitive_type(_Type_INTERVAL_DAY_TIME) + + def month_day_nano_interval(): """ Create instance of an interval type representing months, days and @@ -5779,6 +5791,8 @@ cdef dict _type_aliases = { 'duration[ms]': duration('ms'), 'duration[us]': duration('us'), 'duration[ns]': duration('ns'), + 'month_interval': month_interval(), + 'day_time_interval': day_time_interval(), 'month_day_nano_interval': month_day_nano_interval(), } diff --git a/python/pyarrow/types.py b/python/pyarrow/types.py index d2efe5d3da0c..3feb9ce3b413 100644 --- a/python/pyarrow/types.py +++ b/python/pyarrow/types.py @@ -38,7 +38,8 @@ lib.Type_DECIMAL256} _DATE_TYPES = {lib.Type_DATE32, lib.Type_DATE64} _TIME_TYPES = {lib.Type_TIME32, lib.Type_TIME64} -_INTERVAL_TYPES = {lib.Type_INTERVAL_MONTH_DAY_NANO} +_INTERVAL_TYPES = {lib.Type_INTERVAL_MONTHS, lib.Type_INTERVAL_DAY_TIME, + lib.Type_INTERVAL_MONTH_DAY_NANO} _TEMPORAL_TYPES = ({lib.Type_TIMESTAMP, lib.Type_DURATION} | _TIME_TYPES | _DATE_TYPES | _INTERVAL_TYPES) @@ -395,7 +396,7 @@ def is_dictionary(t): @doc(is_null, datatype="interval") def is_interval(t): - return t.id == lib.Type_INTERVAL_MONTH_DAY_NANO + return t.id in _INTERVAL_TYPES @doc(is_null, datatype="primitive type") From ac0e96f22f6eb5e3d5e65c8844596b4d67752465 Mon Sep 17 00:00:00 2001 From: AlenkaF Date: Wed, 25 Nov 2026 14:59:09 +0100 Subject: [PATCH 02/18] Clean-up double change from cherry-pick --- python/pyarrow/includes/libarrow.pxd | 2 -- python/pyarrow/lib.pyx | 2 -- 2 files changed, 4 deletions(-) diff --git a/python/pyarrow/includes/libarrow.pxd b/python/pyarrow/includes/libarrow.pxd index 2b7353133735..d9b4a07c04c1 100644 --- a/python/pyarrow/includes/libarrow.pxd +++ b/python/pyarrow/includes/libarrow.pxd @@ -149,8 +149,6 @@ cdef extern from "arrow/api.h" namespace "arrow" nogil: _Type_INTERVAL_MONTHS" arrow::Type::INTERVAL_MONTHS" _Type_INTERVAL_DAY_TIME" arrow::Type::INTERVAL_DAY_TIME" _Type_INTERVAL_MONTH_DAY_NANO" arrow::Type::INTERVAL_MONTH_DAY_NANO" - _Type_INTERVAL_DAY_TIME" arrow::Type::INTERVAL_DAY_TIME" - _Type_INTERVAL_MONTHS" arrow::Type::INTERVAL_MONTHS" _Type_BINARY" arrow::Type::BINARY" _Type_STRING" arrow::Type::STRING" diff --git a/python/pyarrow/lib.pyx b/python/pyarrow/lib.pyx index 8ad18e5ab79b..2230947dc753 100644 --- a/python/pyarrow/lib.pyx +++ b/python/pyarrow/lib.pyx @@ -151,8 +151,6 @@ Type_SPARSE_UNION = _Type_SPARSE_UNION Type_DENSE_UNION = _Type_DENSE_UNION Type_DICTIONARY = _Type_DICTIONARY Type_RUN_END_ENCODED = _Type_RUN_END_ENCODED -Type_INTERVAL_MONTHS = _Type_INTERVAL_MONTHS -Type_INTERVAL_DAY_TIME = _Type_INTERVAL_DAY_TIME UnionMode_SPARSE = _UnionMode_SPARSE UnionMode_DENSE = _UnionMode_DENSE From 9c615113bd8dfd9b0328ce5a26fb940bd1155c7d Mon Sep 17 00:00:00 2001 From: AlenkaF Date: Fri, 27 Nov 2026 06:11:33 +0100 Subject: [PATCH 03/18] Add as_py and docstrings --- python/pyarrow/includes/libarrow.pxd | 12 ++++++ python/pyarrow/scalar.pxi | 48 +++++++++++++++++++-- python/pyarrow/tests/test_compute.py | 2 + python/pyarrow/tests/test_scalars.py | 21 ++++++++++ python/pyarrow/types.pxi | 63 ++++++++++++++++++++++++++++ 5 files changed, 142 insertions(+), 4 deletions(-) diff --git a/python/pyarrow/includes/libarrow.pxd b/python/pyarrow/includes/libarrow.pxd index d9b4a07c04c1..291c309a8970 100644 --- a/python/pyarrow/includes/libarrow.pxd +++ b/python/pyarrow/includes/libarrow.pxd @@ -1377,6 +1377,18 @@ cdef extern from "arrow/api.h" namespace "arrow" nogil: cdef cppclass CDurationScalar" arrow::DurationScalar"(CScalar): int64_t value + cdef cppclass CMonthIntervalScalar \ + "arrow::MonthIntervalScalar"(CScalar): + int32_t value + + cdef cppclass CDayMilliseconds" arrow::DayTimeIntervalType::DayMilliseconds": + int32_t days + int32_t milliseconds + + cdef cppclass CDayTimeIntervalScalar \ + "arrow::DayTimeIntervalScalar"(CScalar): + CDayMilliseconds value + cdef cppclass CMonthDayNanoIntervalScalar \ "arrow::MonthDayNanoIntervalScalar"(CScalar): pass diff --git a/python/pyarrow/scalar.pxi b/python/pyarrow/scalar.pxi index 2427ce3ed744..21ef8633e8d8 100644 --- a/python/pyarrow/scalar.pxi +++ b/python/pyarrow/scalar.pxi @@ -917,8 +917,28 @@ cdef class MonthIntervalScalar(Scalar): def __str__(self): return frombytes(self.wrapped.get().ToString()) - def as_py(self): - raise NotImplementedError() + def as_py(self, *, maps_as_pydicts=None): + """ + Return this value as a Python integer. + + Parameters + ---------- + maps_as_pydicts : str, optional, default `None` + Valid values are `None`, 'lossy', or 'strict'. + This parameter is ignored for non-nested Scalars. + + Returns + ------- + int + """ + cdef: + CMonthIntervalScalar* scalar + scalar = self.wrapped.get() + + if not scalar.is_valid: + return None + + return scalar.value cdef class DayTimeIntervalScalar(Scalar): @@ -934,8 +954,28 @@ cdef class DayTimeIntervalScalar(Scalar): def __str__(self): return frombytes(self.wrapped.get().ToString()) - def as_py(self): - raise NotImplementedError() + def as_py(self, *, maps_as_pydicts=None): + """ + Return this value as a tuple of Python integers. + + Parameters + ---------- + maps_as_pydicts : str, optional, default `None` + Valid values are `None`, 'lossy', or 'strict'. + This parameter is ignored for non-nested Scalars. + + Returns + ------- + tuple + """ + cdef: + CDayTimeIntervalScalar* scalar + scalar = self.wrapped.get() + + if not scalar.is_valid: + return None + + return (scalar.value.days, scalar.value.milliseconds) cdef class MonthDayNanoIntervalScalar(Scalar): diff --git a/python/pyarrow/tests/test_compute.py b/python/pyarrow/tests/test_compute.py index a13101dc5868..382cf8d38e4a 100644 --- a/python/pyarrow/tests/test_compute.py +++ b/python/pyarrow/tests/test_compute.py @@ -4651,8 +4651,10 @@ def test_interval_between(): assert isinstance(result, pa.MonthIntervalArray) assert isinstance(result[0], pa.MonthIntervalScalar) assert str(result[0]) == "4M" + assert result.to_pylist() == [4, None, 1429] result = pc.day_time_interval_between(arr1, arr2) assert isinstance(result, pa.DayTimeIntervalArray) assert isinstance(result[0], pa.DayTimeIntervalScalar) assert str(result[0]) == "125d0ms" + assert result.to_pylist() == [(125, 0), None, (43483, 0)] diff --git a/python/pyarrow/tests/test_scalars.py b/python/pyarrow/tests/test_scalars.py index 533a05850522..7146d7281b4d 100644 --- a/python/pyarrow/tests/test_scalars.py +++ b/python/pyarrow/tests/test_scalars.py @@ -529,6 +529,27 @@ def test_duration_nanos_nopandas(): arr[0].as_py() +def test_day_time_and_month_interval(): + arr1 = pa.array( + [datetime.datetime(2020, 1, 1), None, datetime.datetime(1900, 12, 13)], + type=pa.timestamp('s') + ) + arr2 = pa.array( + [datetime.datetime(2020, 5, 5, 1, 30), None, None], + type=pa.timestamp('s') + ) + + arr = pc.month_interval_between(arr1, arr2) + assert isinstance(arr[0].as_py(), int) + assert arr[0].as_py() == 4 + assert arr[1].as_py(maps_as_pydicts="strict") == None + + arr = pc.day_time_interval_between(arr1, arr2) + assert isinstance(arr[0].as_py(), tuple) + assert arr[0].as_py() == (125, 5400000) + assert arr[1].as_py(maps_as_pydicts="strict") == None + + def test_month_day_nano_interval(): triple = pa.MonthDayNano([-3600, 1800, -50]) arr = pa.array([triple]) diff --git a/python/pyarrow/types.pxi b/python/pyarrow/types.pxi index f6ee4089d03b..8d438428de01 100644 --- a/python/pyarrow/types.pxi +++ b/python/pyarrow/types.pxi @@ -4352,12 +4352,75 @@ def duration(unit): def month_interval(): """ + Create instance of an interval type representing months + between two dates. + + Examples + -------- + Create an instance of an month_interval type: + + >>> import pyarrow as pa + >>> pa.month_interval() + DataType(month_interval) + + The type can't be created from Python values yet, but + compute functions return it: + + >>> import pyarrow as pa + >>> import pyarrow.compute as pc + >>> import datetime + >>> arr1 = pa.array([datetime.datetime(2020, 1, 1)], type=pa.timestamp('s')) + >>> arr2 = pa.array([datetime.datetime(2020, 5, 5)], type=pa.timestamp('s')) + + Create an array with month_interval type: + + >>> pc.month_interval_between(arr1, arr2) + + [ + 4M + ] + + or select a scalar with the same type: + + >>> pc.month_interval_between(arr1, arr2)[0] + """ return primitive_type(_Type_INTERVAL_MONTHS) def day_time_interval(): """ + Create instance of an interval type representing day and + milliseconds between two dates. + + Examples + -------- + Create an instance of an day_time_interval type: + + >>> import pyarrow as pa + >>> pa.day_time_interval() + DataType(day_time_interval) + + The type can't be created from Python values yet, but + compute functions return it: + + >>> import pyarrow.compute as pc + >>> import datetime + >>> arr1 = pa.array([datetime.datetime(2020, 1, 1)], type=pa.timestamp('s')) + >>> arr2 = pa.array([datetime.datetime(2020, 5, 5)], type=pa.timestamp('s')) + + Create an array with day_time_interval type: + + >>> pc.day_time_interval_between(arr1, arr2) + + [ + 125d0ms + ] + + or select a scalar with the same type: + + >>> pc.day_time_interval_between(arr1, arr2)[0] + """ return primitive_type(_Type_INTERVAL_DAY_TIME) From 7f48a322c902249310fc49fec02f408fc11d986b Mon Sep 17 00:00:00 2001 From: AlenkaF Date: Fri, 27 Nov 2026 11:17:00 +0100 Subject: [PATCH 04/18] Run linter --- python/pyarrow/tests/test_scalars.py | 4 ++-- python/pyarrow/types.pxi | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/python/pyarrow/tests/test_scalars.py b/python/pyarrow/tests/test_scalars.py index 7146d7281b4d..e086ed3755bc 100644 --- a/python/pyarrow/tests/test_scalars.py +++ b/python/pyarrow/tests/test_scalars.py @@ -542,12 +542,12 @@ def test_day_time_and_month_interval(): arr = pc.month_interval_between(arr1, arr2) assert isinstance(arr[0].as_py(), int) assert arr[0].as_py() == 4 - assert arr[1].as_py(maps_as_pydicts="strict") == None + assert arr[1].as_py(maps_as_pydicts="strict") is None arr = pc.day_time_interval_between(arr1, arr2) assert isinstance(arr[0].as_py(), tuple) assert arr[0].as_py() == (125, 5400000) - assert arr[1].as_py(maps_as_pydicts="strict") == None + assert arr[1].as_py(maps_as_pydicts="strict") is None def test_month_day_nano_interval(): diff --git a/python/pyarrow/types.pxi b/python/pyarrow/types.pxi index 8d438428de01..725d66bef8ae 100644 --- a/python/pyarrow/types.pxi +++ b/python/pyarrow/types.pxi @@ -4396,11 +4396,11 @@ def day_time_interval(): Examples -------- Create an instance of an day_time_interval type: - + >>> import pyarrow as pa >>> pa.day_time_interval() DataType(day_time_interval) - + The type can't be created from Python values yet, but compute functions return it: From c67a89650f648303379378906b4a68036d36c419 Mon Sep 17 00:00:00 2001 From: AlenkaF Date: Fri, 27 Nov 2026 13:08:29 +0100 Subject: [PATCH 05/18] Fix doctest errors --- python/pyarrow/types.pxi | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/python/pyarrow/types.pxi b/python/pyarrow/types.pxi index 725d66bef8ae..8f10760f7fc2 100644 --- a/python/pyarrow/types.pxi +++ b/python/pyarrow/types.pxi @@ -4377,7 +4377,7 @@ def month_interval(): >>> pc.month_interval_between(arr1, arr2) [ - 4M + 4M ] or select a scalar with the same type: @@ -4414,7 +4414,7 @@ def day_time_interval(): >>> pc.day_time_interval_between(arr1, arr2) [ - 125d0ms + 125d0ms ] or select a scalar with the same type: From 2547cb38ed557655167455cc6c8285fbfa1816b9 Mon Sep 17 00:00:00 2001 From: AlenkaF Date: Mon, 30 Nov 2026 13:34:11 +0100 Subject: [PATCH 06/18] Define named tuples in C++ --- python/pyarrow/__init__.py | 4 +- python/pyarrow/array.pxi | 50 ++++++++ python/pyarrow/includes/libarrow.pxd | 8 ++ python/pyarrow/includes/libarrow_python.pxd | 10 ++ python/pyarrow/lib.pyx | 2 + python/pyarrow/scalar.pxi | 26 ++-- python/pyarrow/src/arrow/python/datetime.cc | 133 ++++++++++++++++++-- python/pyarrow/src/arrow/python/datetime.h | 44 +++++++ python/pyarrow/tests/test_compute.py | 6 +- python/pyarrow/tests/test_scalars.py | 11 +- python/pyarrow/tests/test_schema.py | 2 + 11 files changed, 264 insertions(+), 32 deletions(-) diff --git a/python/pyarrow/__init__.py b/python/pyarrow/__init__.py index b0fb74c819b3..4471c5739da2 100644 --- a/python/pyarrow/__init__.py +++ b/python/pyarrow/__init__.py @@ -57,8 +57,8 @@ def parse_git(root, **kwargs): __version__ = None from pyarrow.lib import (BuildInfo, CppBuildInfo, RuntimeInfo, set_timezone_db_path, - MonthDayNano, VersionInfo, build_info, cpp_build_info, - cpp_version, cpp_version_info, runtime_info, + Month, DayTime, MonthDayNano, VersionInfo, build_info, + cpp_build_info, cpp_version, cpp_version_info, runtime_info, cpu_count, set_cpu_count, enable_signal_handlers, io_thread_count, is_opentelemetry_enabled, set_io_thread_count) diff --git a/python/pyarrow/array.pxi b/python/pyarrow/array.pxi index 6e34a91019f4..c8812e608f07 100644 --- a/python/pyarrow/array.pxi +++ b/python/pyarrow/array.pxi @@ -2722,12 +2722,62 @@ cdef class MonthIntervalArray(Array): Concrete class for Arrow arrays of interval[month] data type. """ + def to_pylist(self, *, maps_as_pydicts=None): + """ + Convert to a list of native Python objects. + + pyarrow.Month is used as the native representation. + + Parameters + ---------- + maps_as_pydicts : str, optional, default `None` + Valid values are `None`, 'lossy', or 'strict'. + This parameter is ignored for non-nested Scalars. + + Returns + ------- + lst : list + """ + cdef: + CResult[PyObject*] maybe_py_list + PyObject* py_list + CMonthIntervalArray* array + array = self.sp_array.get() + maybe_py_list = MonthIntervalArrayToPyList(deref(array)) + py_list = GetResultValue(maybe_py_list) + return PyObject_to_object(py_list) + cdef class DayTimeIntervalArray(Array): """ Concrete class for Arrow arrays of interval[day_time] data type. """ + def to_pylist(self, *, maps_as_pydicts=None): + """ + Convert to a list of native Python objects. + + pyarrow.DayTime is used as the native representation. + + Parameters + ---------- + maps_as_pydicts : str, optional, default `None` + Valid values are `None`, 'lossy', or 'strict'. + This parameter is ignored for non-nested Scalars. + + Returns + ------- + lst : list + """ + cdef: + CResult[PyObject*] maybe_py_list + PyObject* py_list + CDayTimeIntervalArray* array + array = self.sp_array.get() + maybe_py_list = DayTimeIntervalArrayToPyList(deref(array)) + py_list = GetResultValue(maybe_py_list) + return PyObject_to_object(py_list) + cdef class MonthDayNanoIntervalArray(Array): """ diff --git a/python/pyarrow/includes/libarrow.pxd b/python/pyarrow/includes/libarrow.pxd index 291c309a8970..7759c8342997 100644 --- a/python/pyarrow/includes/libarrow.pxd +++ b/python/pyarrow/includes/libarrow.pxd @@ -727,6 +727,14 @@ cdef extern from "arrow/api.h" namespace "arrow" nogil: cdef cppclass CDurationArray" arrow::DurationArray"(CArray): int64_t Value(int64_t i) + cdef cppclass CMonthIntervalArray \ + "arrow::MonthIntervalArray"(CArray): + pass + + cdef cppclass CDayTimeIntervalArray \ + "arrow::DayTimeIntervalArray"(CArray): + pass + cdef cppclass CMonthDayNanoIntervalArray \ "arrow::MonthDayNanoIntervalArray"(CArray): pass diff --git a/python/pyarrow/includes/libarrow_python.pxd b/python/pyarrow/includes/libarrow_python.pxd index e6fbd23e5913..41632f574814 100644 --- a/python/pyarrow/includes/libarrow_python.pxd +++ b/python/pyarrow/includes/libarrow_python.pxd @@ -38,9 +38,19 @@ cdef extern from "arrow/python/api.h" namespace "arrow::py": cdef extern from "arrow/python/api.h" namespace "arrow::py::internal": + object NewMonthTupleType() + object NewDayTimeTupleType() object NewMonthDayNanoTupleType() + CResult[PyObject*] MonthIntervalArrayToPyList( + const CMonthIntervalArray& array) + CResult[PyObject*] DayTimeIntervalArrayToPyList( + const CDayTimeIntervalArray& array) CResult[PyObject*] MonthDayNanoIntervalArrayToPyList( const CMonthDayNanoIntervalArray& array) + CResult[PyObject*] MonthIntervalScalarToPyObject( + const CMonthIntervalScalar& scalar) + CResult[PyObject*] DayTimeIntervalScalarToPyObject( + const CDayTimeIntervalScalar& scalar) CResult[PyObject*] MonthDayNanoIntervalScalarToPyObject( const CMonthDayNanoIntervalScalar& scalar) diff --git a/python/pyarrow/lib.pyx b/python/pyarrow/lib.pyx index 2230947dc753..c89350879e0b 100644 --- a/python/pyarrow/lib.pyx +++ b/python/pyarrow/lib.pyx @@ -49,6 +49,8 @@ if np is not None: import_pyarrow() +Month = NewMonthTupleType() +DayTime = NewDayTimeTupleType() MonthDayNano = NewMonthDayNanoTupleType() diff --git a/python/pyarrow/scalar.pxi b/python/pyarrow/scalar.pxi index 21ef8633e8d8..5c5e2c5db75c 100644 --- a/python/pyarrow/scalar.pxi +++ b/python/pyarrow/scalar.pxi @@ -919,7 +919,7 @@ cdef class MonthIntervalScalar(Scalar): def as_py(self, *, maps_as_pydicts=None): """ - Return this value as a Python integer. + Return this value as a pyarrow.Month. Parameters ---------- @@ -929,16 +929,15 @@ cdef class MonthIntervalScalar(Scalar): Returns ------- - int + pyarrow.Month """ cdef: + PyObject* val CMonthIntervalScalar* scalar scalar = self.wrapped.get() - - if not scalar.is_valid: - return None - - return scalar.value + val = GetResultValue(MonthIntervalScalarToPyObject( + deref(scalar))) + return PyObject_to_object(val) cdef class DayTimeIntervalScalar(Scalar): @@ -956,7 +955,7 @@ cdef class DayTimeIntervalScalar(Scalar): def as_py(self, *, maps_as_pydicts=None): """ - Return this value as a tuple of Python integers. + Return this value as a pyarrow.DayTime. Parameters ---------- @@ -966,16 +965,15 @@ cdef class DayTimeIntervalScalar(Scalar): Returns ------- - tuple + pyarrow.DayTime """ cdef: + PyObject* val CDayTimeIntervalScalar* scalar scalar = self.wrapped.get() - - if not scalar.is_valid: - return None - - return (scalar.value.days, scalar.value.milliseconds) + val = GetResultValue(DayTimeIntervalScalarToPyObject( + deref(scalar))) + return PyObject_to_object(val) cdef class MonthDayNanoIntervalScalar(Scalar): diff --git a/python/pyarrow/src/arrow/python/datetime.cc b/python/pyarrow/src/arrow/python/datetime.cc index 6a835c2d37ce..ba31cc3f0828 100644 --- a/python/pyarrow/src/arrow/python/datetime.cc +++ b/python/pyarrow/src/arrow/python/datetime.cc @@ -52,23 +52,36 @@ bool MatchFixedOffset(const std::string& tz, std::string_view* sign, return RegexMatch(regex, tz, {sign, hour, minute}); } -constexpr char* NonConst(const char* st) { - // Hack for python versions < 3.7 where members of PyStruct members - // where non-const (C++ doesn't like assigning string literals to these types) - return const_cast(st); -} +static PyTypeObject MonthTupleType = {}; + +static PyStructSequence_Field MonthField[] = { + {"months", "The number of months in the interval"}, {nullptr, nullptr}}; + +static PyStructSequence_Desc MonthTupleDesc = { + "Month", "A calendar interval consisting of months.", MonthField, + /*n_in_sequence=*/1}; + +static PyTypeObject DayTimeTupleType = {}; + +static PyStructSequence_Field DayTimeField[] = { + {"days", "The number days in the interval"}, + {"milliseconds", "The number of milliseconds in the interval"}, + {nullptr, nullptr}}; + +static PyStructSequence_Desc DayTimeTupleDesc = { + "DayTime", "A calendar interval consisting of days and milliseconds.", DayTimeField, + /*n_in_sequence=*/2}; static PyTypeObject MonthDayNanoTupleType = {}; static PyStructSequence_Field MonthDayNanoField[] = { - {NonConst("months"), NonConst("The number of months in the interval")}, - {NonConst("days"), NonConst("The number days in the interval")}, - {NonConst("nanoseconds"), NonConst("The number of nanoseconds in the interval")}, + {"months", "The number of months in the interval"}, + {"days", "The number days in the interval"}, + {"nanoseconds", "The number of nanoseconds in the interval"}, {nullptr, nullptr}}; static PyStructSequence_Desc MonthDayNanoTupleDesc = { - NonConst("MonthDayNano"), - NonConst("A calendar interval consisting of months, days and nanoseconds."), + "MonthDayNano", "A calendar interval consisting of months, days and nanoseconds.", MonthDayNanoField, /*n_in_sequence=*/3}; @@ -273,6 +286,26 @@ static inline Status PyDate_convert_int(int64_t val, const DateUnit unit, int64_ return Status::OK(); } +PyObject* NewMonthTupleType() { + if (MonthTupleType.tp_name == nullptr) { + if (PyStructSequence_InitType2(&MonthTupleType, &MonthTupleDesc) != 0) { + Py_FatalError("Could not initialize MonthTuple"); + } + } + Py_INCREF(&MonthTupleType); + return (PyObject*)&MonthTupleType; +} + +PyObject* NewDayTimeTupleType() { + if (DayTimeTupleType.tp_name == nullptr) { + if (PyStructSequence_InitType2(&DayTimeTupleType, &DayTimeTupleDesc) != 0) { + Py_FatalError("Could not initialize DayTimeTuple"); + } + } + Py_INCREF(&DayTimeTupleType); + return (PyObject*)&DayTimeTupleType; +} + PyObject* NewMonthDayNanoTupleType() { if (MonthDayNanoTupleType.tp_name == nullptr) { if (PyStructSequence_InitType2(&MonthDayNanoTupleType, &MonthDayNanoTupleDesc) != 0) { @@ -594,6 +627,27 @@ Result TzinfoToString(PyObject* tzinfo) { return PyTZInfo_utcoffset_hhmm(tzinfo); } +PyObject* MonthIntervalToNamedTuple(MonthIntervalType::c_type interval) { + OwnedRef tuple(PyStructSequence_New(&MonthTupleType)); + if (ARROW_PREDICT_FALSE(tuple.obj() == nullptr)) { + return nullptr; + } + PyStructSequence_SetItem(tuple.obj(), /*pos=*/0, PyLong_FromLong(interval)); + return tuple.detach(); +} + +PyObject* DayTimeIntervalToNamedTuple( + const DayTimeIntervalType::DayMilliseconds& interval) { + OwnedRef tuple(PyStructSequence_New(&DayTimeTupleType)); + if (ARROW_PREDICT_FALSE(tuple.obj() == nullptr)) { + return nullptr; + } + PyStructSequence_SetItem(tuple.obj(), /*pos=*/0, PyLong_FromLong(interval.days)); + PyStructSequence_SetItem(tuple.obj(), /*pos=*/1, + PyLong_FromLong(interval.milliseconds)); + return tuple.detach(); +} + PyObject* MonthDayNanoIntervalToNamedTuple( const MonthDayNanoIntervalType::MonthDayNanos& interval) { OwnedRef tuple(PyStructSequence_New(&MonthDayNanoTupleType)); @@ -642,6 +696,47 @@ struct PyListAssigner { } // namespace +Result MonthIntervalArrayToPyList(const MonthIntervalArray& array) { + OwnedRef out_list(PyList_New(array.length())); + RETURN_IF_PYERROR(); + PyListAssigner out_objects(out_list.obj()); + auto& interval_array = arrow::internal::checked_cast(array); + RETURN_NOT_OK(internal::WriteArrayObjects( + interval_array, + [&](MonthIntervalType::c_type interval, PyListAssigner& out) { + PyObject* tuple = internal::MonthIntervalToNamedTuple(interval); + if (ARROW_PREDICT_FALSE(tuple == nullptr)) { + RETURN_IF_PYERROR(); + } + + *out = tuple; + return Status::OK(); + }, + out_objects)); + return out_list.detach(); +} + +Result DayTimeIntervalArrayToPyList(const DayTimeIntervalArray& array) { + OwnedRef out_list(PyList_New(array.length())); + RETURN_IF_PYERROR(); + PyListAssigner out_objects(out_list.obj()); + auto& interval_array = + arrow::internal::checked_cast(array); + RETURN_NOT_OK(internal::WriteArrayObjects( + interval_array, + [&](const DayTimeIntervalType::DayMilliseconds& interval, PyListAssigner& out) { + PyObject* tuple = internal::DayTimeIntervalToNamedTuple(interval); + if (ARROW_PREDICT_FALSE(tuple == nullptr)) { + RETURN_IF_PYERROR(); + } + + *out = tuple; + return Status::OK(); + }, + out_objects)); + return out_list.detach(); +} + Result MonthDayNanoIntervalArrayToPyList( const MonthDayNanoIntervalArray& array) { OwnedRef out_list(PyList_New(array.length())); @@ -664,6 +759,24 @@ Result MonthDayNanoIntervalArrayToPyList( return out_list.detach(); } +Result MonthIntervalScalarToPyObject(const MonthIntervalScalar& scalar) { + if (scalar.is_valid) { + return internal::MonthIntervalToNamedTuple(scalar.value); + } else { + Py_INCREF(Py_None); + return Py_None; + } +} + +Result DayTimeIntervalScalarToPyObject(const DayTimeIntervalScalar& scalar) { + if (scalar.is_valid) { + return internal::DayTimeIntervalToNamedTuple(scalar.value); + } else { + Py_INCREF(Py_None); + return Py_None; + } +} + Result MonthDayNanoIntervalScalarToPyObject( const MonthDayNanoIntervalScalar& scalar) { if (scalar.is_valid) { diff --git a/python/pyarrow/src/arrow/python/datetime.h b/python/pyarrow/src/arrow/python/datetime.h index 84f46fe2d19c..1569ab1afb52 100644 --- a/python/pyarrow/src/arrow/python/datetime.h +++ b/python/pyarrow/src/arrow/python/datetime.h @@ -53,6 +53,12 @@ ARROW_PYTHON_EXPORT void InitDatetime(); #endif +ARROW_PYTHON_EXPORT +PyObject* NewMonthTupleType(); + +ARROW_PYTHON_EXPORT +PyObject* NewDayTimeTupleType(); + // Returns the MonthDayNano namedtuple type (increments the reference count). ARROW_PYTHON_EXPORT PyObject* NewMonthDayNanoTupleType(); @@ -203,6 +209,44 @@ Result StringToTzinfo(const std::string& tz, bool prefer_zoneinfo = t ARROW_PYTHON_EXPORT Result TzinfoToString(PyObject* pytzinfo); +/// \brief Convert Month to a python namedtuple. +/// +/// Return a named tuple (pyarrow.Month) containing "months". +/// +/// GIL must be held when calling this method. +ARROW_PYTHON_EXPORT +PyObject* MonthIntervalToNamedTuple(MonthIntervalType::c_type interval); + +/// \brief Convert the given Array to a PyList object containing +/// pyarrow.Month objects. +ARROW_PYTHON_EXPORT +Result MonthIntervalArrayToPyList(const MonthIntervalArray& array); + +/// \brief Convert the Scalar object to a pyarrow.Month (or None if +/// is isn't valid). +ARROW_PYTHON_EXPORT +Result MonthIntervalScalarToPyObject(const MonthIntervalScalar& scalar); + +/// \brief Convert DayTime to a python namedtuple. +/// +/// Return a named tuple (pyarrow.DayTime) containing attributes +/// "days", "milliseconds" in the given order. +/// +/// GIL must be held when calling this method. +ARROW_PYTHON_EXPORT +PyObject* DayTimeIntervalToNamedTuple( + const DayTimeIntervalType::DayMilliseconds& interval); + +/// \brief Convert the given Array to a PyList object containing +/// pyarrow.DayTime objects. +ARROW_PYTHON_EXPORT +Result DayTimeIntervalArrayToPyList(const DayTimeIntervalArray& array); + +/// \brief Convert the Scalar object to a pyarrow.DayTime (or None if +/// is isn't valid). +ARROW_PYTHON_EXPORT +Result DayTimeIntervalScalarToPyObject(const DayTimeIntervalScalar& scalar); + /// \brief Convert MonthDayNano to a python namedtuple. /// /// Return a named tuple (pyarrow.MonthDayNano) containing attributes diff --git a/python/pyarrow/tests/test_compute.py b/python/pyarrow/tests/test_compute.py index 382cf8d38e4a..7e84e5e524f6 100644 --- a/python/pyarrow/tests/test_compute.py +++ b/python/pyarrow/tests/test_compute.py @@ -4651,10 +4651,12 @@ def test_interval_between(): assert isinstance(result, pa.MonthIntervalArray) assert isinstance(result[0], pa.MonthIntervalScalar) assert str(result[0]) == "4M" - assert result.to_pylist() == [4, None, 1429] + assert result.to_pylist() == [pa.Month([4]), None, pa.Month([1429])] result = pc.day_time_interval_between(arr1, arr2) assert isinstance(result, pa.DayTimeIntervalArray) assert isinstance(result[0], pa.DayTimeIntervalScalar) assert str(result[0]) == "125d0ms" - assert result.to_pylist() == [(125, 0), None, (43483, 0)] + assert result.to_pylist() == [pa.DayTime([125, 0]), + None, + pa.DayTime([43483, 0])] diff --git a/python/pyarrow/tests/test_scalars.py b/python/pyarrow/tests/test_scalars.py index e086ed3755bc..e8223a224881 100644 --- a/python/pyarrow/tests/test_scalars.py +++ b/python/pyarrow/tests/test_scalars.py @@ -540,13 +540,16 @@ def test_day_time_and_month_interval(): ) arr = pc.month_interval_between(arr1, arr2) - assert isinstance(arr[0].as_py(), int) - assert arr[0].as_py() == 4 + assert isinstance(arr[0].as_py(), pa.Month) + assert arr[0].as_py() == pa.Month([4]) + assert arr[0].as_py().months == 4 assert arr[1].as_py(maps_as_pydicts="strict") is None arr = pc.day_time_interval_between(arr1, arr2) - assert isinstance(arr[0].as_py(), tuple) - assert arr[0].as_py() == (125, 5400000) + assert isinstance(arr[0].as_py(), pa.DayTime) + assert arr[0].as_py() == pa.DayTime([125, 5400000]) + assert arr[0].as_py().days == 125 + assert arr[0].as_py().milliseconds == 5400000 assert arr[1].as_py(maps_as_pydicts="strict") is None diff --git a/python/pyarrow/tests/test_schema.py b/python/pyarrow/tests/test_schema.py index 0ed3cec1408c..b96363f5583f 100644 --- a/python/pyarrow/tests/test_schema.py +++ b/python/pyarrow/tests/test_schema.py @@ -145,6 +145,8 @@ def test_type_for_alias(): ('duration[ms]', pa.duration('ms')), ('duration[us]', pa.duration('us')), ('duration[ns]', pa.duration('ns')), + ('month_interval', pa.month_interval()), + ('day_time_interval', pa.day_time_interval()), ('month_day_nano_interval', pa.month_day_nano_interval()), ] From f264ecf4b982525704cf0ee6fae8c8040580fc42 Mon Sep 17 00:00:00 2001 From: AlenkaF Date: Wed, 2 Dec 2026 09:26:36 +0100 Subject: [PATCH 07/18] Add stubs and tests, add value properties to scalar classes --- python/pyarrow-stubs-tests/test_scalar.py | 12 ++++++++++++ python/pyarrow-stubs-tests/test_types.py | 15 +++++++++++++++ python/pyarrow-stubs/__init__.pyi | 8 ++++++++ python/pyarrow-stubs/__lib/array.pyi | 4 ++++ python/pyarrow-stubs/__lib/scalar.pyi | 18 ++++++++++++++++++ python/pyarrow-stubs/__lib/types.pyi | 8 ++++++++ python/pyarrow-stubs/_stubs_typing.pyi | 2 ++ python/pyarrow-stubs/lib.pyi | 13 +++++++++++++ python/pyarrow-stubs/types.pyi | 6 +++++- python/pyarrow/scalar.pxi | 14 ++++++++++++++ python/pyarrow/tests/test_scalars.py | 4 ++++ 11 files changed, 103 insertions(+), 1 deletion(-) diff --git a/python/pyarrow-stubs-tests/test_scalar.py b/python/pyarrow-stubs-tests/test_scalar.py index 9f6bcbfc9553..e27a2229680f 100644 --- a/python/pyarrow-stubs-tests/test_scalar.py +++ b/python/pyarrow-stubs-tests/test_scalar.py @@ -153,6 +153,18 @@ def test_temporal_scalars() -> None: check(assert_type(interval.as_py(), pa.MonthDayNano | None), pa.MonthDayNano) + # TODO(GH-29828 follow-up): use pa.scalar(pa.Month([4])) and + # pa.scalar(pa.DayTime([1, 0])) once Python to Arrow conversion is done + month = cast(pa.MonthIntervalScalar, + pa.array([4], pa.int32()).view(pa.month_interval())[0]) + check(assert_type(month.value, pa.Month | None), pa.Month) + check(assert_type(month.as_py(), pa.Month | None), pa.Month) + + day_time = cast(pa.DayTimeIntervalScalar, + pa.array([1], pa.int64()).view(pa.day_time_interval())[0]) + check(assert_type(day_time.value, pa.DayTime | None), pa.DayTime) + check(assert_type(day_time.as_py(), pa.DayTime | None), pa.DayTime) + def test_binary_scalars() -> None: binary = pa.scalar(b"abc") diff --git a/python/pyarrow-stubs-tests/test_types.py b/python/pyarrow-stubs-tests/test_types.py index ebbed90353da..f20cffbc6924 100644 --- a/python/pyarrow-stubs-tests/test_types.py +++ b/python/pyarrow-stubs-tests/test_types.py @@ -24,10 +24,13 @@ import pyarrow as pa from pyarrow._stubs_typing import ( BoolType, + DayTimeIntervalType, Int16Type, Int32Type, Int64Type, IntegerType, + MonthDayNanoIntervalType, + MonthIntervalType, StringType, ) @@ -61,6 +64,8 @@ def test_temporal_types() -> None: check(assert_type(pa.time32("s").unit, Literal["s", "ms"]), str) check(assert_type(pa.time64("ns").unit, Literal["us", "ns"]), str) check(assert_type(pa.duration("us"), pa.DurationType), pa.DurationType) + check(assert_type(pa.month_interval(), MonthIntervalType), pa.DataType) + check(assert_type(pa.day_time_interval(), DayTimeIntervalType), pa.DataType) def test_decimal_types() -> None: @@ -164,6 +169,16 @@ def test_type_predicates_narrow() -> None: pa.Decimal64Type, ) + interval = _erase(pa.month_interval()) + assert pa.types.is_interval(interval) + check( + assert_type( + interval, + MonthIntervalType | DayTimeIntervalType | MonthDayNanoIntervalType, + ), + pa.DataType, + ) + # Decimal types subclass FixedSizeBinaryType, but don't match it, so # they must not be narrowed away when the check fails. dec128 = _erase(pa.decimal128(5, 2)) diff --git a/python/pyarrow-stubs/__init__.pyi b/python/pyarrow-stubs/__init__.pyi index d0f4f25f6cf1..0e2f71005803 100644 --- a/python/pyarrow-stubs/__init__.pyi +++ b/python/pyarrow-stubs/__init__.pyi @@ -128,6 +128,12 @@ from pyarrow.lib import ( MapType as MapType, MemoryManager as MemoryManager, MemoryPool as MemoryPool, + Month as Month, + MonthIntervalArray as MonthIntervalArray, + MonthIntervalScalar as MonthIntervalScalar, + DayTime as DayTime, + DayTimeIntervalArray as DayTimeIntervalArray, + DayTimeIntervalScalar as DayTimeIntervalScalar, MonthDayNano as MonthDayNano, MonthDayNanoIntervalArray as MonthDayNanoIntervalArray, MonthDayNanoIntervalScalar as MonthDayNanoIntervalScalar, @@ -236,6 +242,8 @@ from pyarrow.lib import ( logging_memory_pool as logging_memory_pool, map_ as map_, mimalloc_memory_pool as mimalloc_memory_pool, + month_interval as month_interval, + day_time_interval as day_time_interval, month_day_nano_interval as month_day_nano_interval, null as null, nulls as nulls, diff --git a/python/pyarrow-stubs/__lib/array.pyi b/python/pyarrow-stubs/__lib/array.pyi index 4814cdbc1e73..87244f364193 100644 --- a/python/pyarrow-stubs/__lib/array.pyi +++ b/python/pyarrow-stubs/__lib/array.pyi @@ -345,6 +345,8 @@ class TimestampArray(NumericArray): ... class Time32Array(NumericArray): ... class Time64Array(NumericArray): ... class DurationArray(NumericArray): ... +class MonthIntervalArray(Array): ... +class DayTimeIntervalArray(Array): ... class MonthDayNanoIntervalArray(Array): ... class HalfFloatArray(FloatingPointArray): ... class FloatArray(FloatingPointArray): ... @@ -649,6 +651,8 @@ __all__ = [ "Time32Array", "Time64Array", "DurationArray", + "MonthIntervalArray", + "DayTimeIntervalArray", "MonthDayNanoIntervalArray", "HalfFloatArray", "FloatArray", diff --git a/python/pyarrow-stubs/__lib/scalar.pyi b/python/pyarrow-stubs/__lib/scalar.pyi index 8cf5b8efb2e9..19c0b58d4713 100644 --- a/python/pyarrow-stubs/__lib/scalar.pyi +++ b/python/pyarrow-stubs/__lib/scalar.pyi @@ -31,6 +31,8 @@ from pyarrow.lib import ( ChunkedArray, DataType, MemoryPool, + Month, + DayTime, MonthDayNano, Tensor, _Weakrefable, @@ -224,6 +226,20 @@ class DurationScalar(Scalar): self, *, maps_as_pydicts: MapsAsPydicts | None = None ) -> dt.timedelta | None: ... +class MonthIntervalScalar(Scalar): + @property + def value(self) -> Month | None: ... + def as_py( + self, *, maps_as_pydicts: MapsAsPydicts | None = None + ) -> Month | None: ... + +class DayTimeIntervalScalar(Scalar): + @property + def value(self) -> DayTime | None: ... + def as_py( + self, *, maps_as_pydicts: MapsAsPydicts | None = None + ) -> DayTime | None: ... + class MonthDayNanoIntervalScalar(Scalar): @property def value(self) -> MonthDayNano | None: ... @@ -417,6 +433,8 @@ __all__ = [ "Time64Scalar", "TimestampScalar", "DurationScalar", + "MonthIntervalScalar", + "DayTimeIntervalScalar", "MonthDayNanoIntervalScalar", "BinaryScalar", "LargeBinaryScalar", diff --git a/python/pyarrow-stubs/__lib/types.pyi b/python/pyarrow-stubs/__lib/types.pyi index 7810d33b762c..cad39f04ef6f 100644 --- a/python/pyarrow-stubs/__lib/types.pyi +++ b/python/pyarrow-stubs/__lib/types.pyi @@ -38,6 +38,8 @@ from pyarrow._stubs_typing import ( IntegerType, LargeBinaryType, LargeStringType, + MonthIntervalType, + DayTimeIntervalType, MonthDayNanoIntervalType, NullType, StringType, @@ -344,6 +346,8 @@ _DataTypeAlias: TypeAlias = Literal[ "duration[ms]", "duration[us]", "duration[ns]", + "month_interval", + "day_time_interval", "month_day_nano_interval", ] _DataTypeAliasInput: TypeAlias = _DataTypeAlias | str @@ -493,6 +497,8 @@ def timestamp( def time32(unit: _Time32Unit | str) -> Time32Type: ... def time64(unit: _Time64Unit | str) -> Time64Type: ... def duration(unit: TimeUnit | str) -> DurationType: ... +def month_interval() -> MonthIntervalType: ... +def day_time_interval() -> DayTimeIntervalType: ... def month_day_nano_interval() -> MonthDayNanoIntervalType: ... def date32() -> Date32Type: ... def date64() -> Date64Type: ... @@ -626,6 +632,8 @@ __all__ = [ "time32", "time64", "duration", + "month_interval", + "day_time_interval", "month_day_nano_interval", "date32", "date64", diff --git a/python/pyarrow-stubs/_stubs_typing.pyi b/python/pyarrow-stubs/_stubs_typing.pyi index 17ee2cffc316..90a79999511e 100644 --- a/python/pyarrow-stubs/_stubs_typing.pyi +++ b/python/pyarrow-stubs/_stubs_typing.pyi @@ -72,6 +72,8 @@ class Float32Type(lib.DataType): ... class Float64Type(lib.DataType): ... class Date32Type(lib.DataType): ... class Date64Type(lib.DataType): ... +class MonthIntervalType(lib.DataType): ... +class DayTimeIntervalType(lib.DataType): ... class MonthDayNanoIntervalType(lib.DataType): ... class StringType(lib.DataType): ... class LargeStringType(lib.DataType): ... diff --git a/python/pyarrow-stubs/lib.pyi b/python/pyarrow-stubs/lib.pyi index 74624bfbcd47..818241e224e1 100644 --- a/python/pyarrow-stubs/lib.pyi +++ b/python/pyarrow-stubs/lib.pyi @@ -33,6 +33,19 @@ from pyarrow.__lib.table import * # noqa: F401,F403 from pyarrow.__lib.tensor import * # noqa: F401,F403 from pyarrow.__lib.types import * # noqa: F401,F403 +@final +class Month(tuple[int]): + months: int + + def __new__(cls, sequence: tuple[int] | list[int]) -> Self: ... + +@final +class DayTime(tuple[int, int]): + days: int + milliseconds: int + + def __new__(cls, sequence: tuple[int, int] | list[int]) -> Self: ... + @final class MonthDayNano(tuple[int, int, int]): months: int diff --git a/python/pyarrow-stubs/types.pyi b/python/pyarrow-stubs/types.pyi index 8f8773b08d56..c6c9fc4e765e 100644 --- a/python/pyarrow-stubs/types.pyi +++ b/python/pyarrow-stubs/types.pyi @@ -40,6 +40,8 @@ from pyarrow._stubs_typing import ( IntegerType, LargeBinaryType, LargeStringType, + MonthIntervalType, + DayTimeIntervalType, MonthDayNanoIntervalType, NullType, StringType, @@ -79,7 +81,9 @@ _Floating: TypeAlias = Float16Type | Float32Type | Float64Type _Decimal: TypeAlias = Decimal32Type | Decimal64Type | Decimal128Type | Decimal256Type _Date: TypeAlias = Date32Type | Date64Type _Time: TypeAlias = Time32Type | Time64Type -_Interval: TypeAlias = MonthDayNanoIntervalType +_Interval: TypeAlias = ( + MonthIntervalType | DayTimeIntervalType | MonthDayNanoIntervalType +) _Temporal: TypeAlias = TimestampType | DurationType | _Time | _Date | _Interval _Union: TypeAlias = SparseUnionType | DenseUnionType _Nested: TypeAlias = ( diff --git a/python/pyarrow/scalar.pxi b/python/pyarrow/scalar.pxi index 5c5e2c5db75c..ef7a02266f81 100644 --- a/python/pyarrow/scalar.pxi +++ b/python/pyarrow/scalar.pxi @@ -909,6 +909,13 @@ cdef class MonthIntervalScalar(Scalar): Concrete class for month interval scalars. """ + @property + def value(self): + """ + Same as self.as_py() + """ + return self.as_py() + def __repr__(self): return ''.format( self.__class__.__name__, frombytes(self.wrapped.get().ToString()) @@ -945,6 +952,13 @@ cdef class DayTimeIntervalScalar(Scalar): Concrete class for day-time interval scalars. """ + @property + def value(self): + """ + Same as self.as_py() + """ + return self.as_py() + def __repr__(self): return ''.format( self.__class__.__name__, frombytes(self.wrapped.get().ToString()) diff --git a/python/pyarrow/tests/test_scalars.py b/python/pyarrow/tests/test_scalars.py index e8223a224881..aa9ca8ad0f79 100644 --- a/python/pyarrow/tests/test_scalars.py +++ b/python/pyarrow/tests/test_scalars.py @@ -543,14 +543,18 @@ def test_day_time_and_month_interval(): assert isinstance(arr[0].as_py(), pa.Month) assert arr[0].as_py() == pa.Month([4]) assert arr[0].as_py().months == 4 + assert arr[0].value == arr[0].as_py() assert arr[1].as_py(maps_as_pydicts="strict") is None + assert arr[1].value is None arr = pc.day_time_interval_between(arr1, arr2) assert isinstance(arr[0].as_py(), pa.DayTime) assert arr[0].as_py() == pa.DayTime([125, 5400000]) assert arr[0].as_py().days == 125 assert arr[0].as_py().milliseconds == 5400000 + assert arr[0].value == arr[0].as_py() assert arr[1].as_py(maps_as_pydicts="strict") is None + assert arr[1].value is None def test_month_day_nano_interval(): From 7964475ab841c960197f3f44c692961f6ed72e24 Mon Sep 17 00:00:00 2001 From: AlenkaF Date: Wed, 2 Dec 2026 12:53:47 +0100 Subject: [PATCH 08/18] Add cpu assert to all three interval classes --- python/pyarrow/array.pxi | 3 +++ 1 file changed, 3 insertions(+) diff --git a/python/pyarrow/array.pxi b/python/pyarrow/array.pxi index c8812e608f07..ac3b87334638 100644 --- a/python/pyarrow/array.pxi +++ b/python/pyarrow/array.pxi @@ -2738,6 +2738,7 @@ cdef class MonthIntervalArray(Array): ------- lst : list """ + self._assert_cpu() cdef: CResult[PyObject*] maybe_py_list PyObject* py_list @@ -2769,6 +2770,7 @@ cdef class DayTimeIntervalArray(Array): ------- lst : list """ + self._assert_cpu() cdef: CResult[PyObject*] maybe_py_list PyObject* py_list @@ -2800,6 +2802,7 @@ cdef class MonthDayNanoIntervalArray(Array): ------- lst : list """ + self._assert_cpu() cdef: CResult[PyObject*] maybe_py_list PyObject* py_list From b8d8a7a55743f1d55a9862b72c4ba530a2524832 Mon Sep 17 00:00:00 2001 From: AlenkaF Date: Wed, 2 Dec 2026 13:03:38 +0100 Subject: [PATCH 09/18] Remove __repr__ and__str__ overrides --- python/pyarrow/scalar.pxi | 16 ---------------- python/pyarrow/tests/test_compute.py | 4 ++-- python/pyarrow/types.pxi | 4 ++-- 3 files changed, 4 insertions(+), 20 deletions(-) diff --git a/python/pyarrow/scalar.pxi b/python/pyarrow/scalar.pxi index ef7a02266f81..41d8e8fb831d 100644 --- a/python/pyarrow/scalar.pxi +++ b/python/pyarrow/scalar.pxi @@ -916,14 +916,6 @@ cdef class MonthIntervalScalar(Scalar): """ return self.as_py() - def __repr__(self): - return ''.format( - self.__class__.__name__, frombytes(self.wrapped.get().ToString()) - ) - - def __str__(self): - return frombytes(self.wrapped.get().ToString()) - def as_py(self, *, maps_as_pydicts=None): """ Return this value as a pyarrow.Month. @@ -959,14 +951,6 @@ cdef class DayTimeIntervalScalar(Scalar): """ return self.as_py() - def __repr__(self): - return ''.format( - self.__class__.__name__, frombytes(self.wrapped.get().ToString()) - ) - - def __str__(self): - return frombytes(self.wrapped.get().ToString()) - def as_py(self, *, maps_as_pydicts=None): """ Return this value as a pyarrow.DayTime. diff --git a/python/pyarrow/tests/test_compute.py b/python/pyarrow/tests/test_compute.py index 7e84e5e524f6..c687a708cf5f 100644 --- a/python/pyarrow/tests/test_compute.py +++ b/python/pyarrow/tests/test_compute.py @@ -4650,13 +4650,13 @@ def test_interval_between(): result = pc.month_interval_between(arr1, arr2) assert isinstance(result, pa.MonthIntervalArray) assert isinstance(result[0], pa.MonthIntervalScalar) - assert str(result[0]) == "4M" + assert str(result[0]) == "Month(months=4)" assert result.to_pylist() == [pa.Month([4]), None, pa.Month([1429])] result = pc.day_time_interval_between(arr1, arr2) assert isinstance(result, pa.DayTimeIntervalArray) assert isinstance(result[0], pa.DayTimeIntervalScalar) - assert str(result[0]) == "125d0ms" + assert str(result[0]) == "DayTime(days=125, milliseconds=0)" assert result.to_pylist() == [pa.DayTime([125, 0]), None, pa.DayTime([43483, 0])] diff --git a/python/pyarrow/types.pxi b/python/pyarrow/types.pxi index 8f10760f7fc2..ef326d7329ce 100644 --- a/python/pyarrow/types.pxi +++ b/python/pyarrow/types.pxi @@ -4383,7 +4383,7 @@ def month_interval(): or select a scalar with the same type: >>> pc.month_interval_between(arr1, arr2)[0] - + """ return primitive_type(_Type_INTERVAL_MONTHS) @@ -4420,7 +4420,7 @@ def day_time_interval(): or select a scalar with the same type: >>> pc.day_time_interval_between(arr1, arr2)[0] - + """ return primitive_type(_Type_INTERVAL_DAY_TIME) From 0f54a4d05d53407ccdc72c6faabff6a2bf58a0a9 Mon Sep 17 00:00:00 2001 From: AlenkaF Date: Wed, 2 Dec 2026 13:09:26 +0100 Subject: [PATCH 10/18] Remove redundant cast --- python/pyarrow/src/arrow/python/datetime.cc | 11 +++-------- 1 file changed, 3 insertions(+), 8 deletions(-) diff --git a/python/pyarrow/src/arrow/python/datetime.cc b/python/pyarrow/src/arrow/python/datetime.cc index ba31cc3f0828..c63f7e9e89de 100644 --- a/python/pyarrow/src/arrow/python/datetime.cc +++ b/python/pyarrow/src/arrow/python/datetime.cc @@ -700,9 +700,8 @@ Result MonthIntervalArrayToPyList(const MonthIntervalArray& array) { OwnedRef out_list(PyList_New(array.length())); RETURN_IF_PYERROR(); PyListAssigner out_objects(out_list.obj()); - auto& interval_array = arrow::internal::checked_cast(array); RETURN_NOT_OK(internal::WriteArrayObjects( - interval_array, + array, [&](MonthIntervalType::c_type interval, PyListAssigner& out) { PyObject* tuple = internal::MonthIntervalToNamedTuple(interval); if (ARROW_PREDICT_FALSE(tuple == nullptr)) { @@ -720,10 +719,8 @@ Result DayTimeIntervalArrayToPyList(const DayTimeIntervalArray& array OwnedRef out_list(PyList_New(array.length())); RETURN_IF_PYERROR(); PyListAssigner out_objects(out_list.obj()); - auto& interval_array = - arrow::internal::checked_cast(array); RETURN_NOT_OK(internal::WriteArrayObjects( - interval_array, + array, [&](const DayTimeIntervalType::DayMilliseconds& interval, PyListAssigner& out) { PyObject* tuple = internal::DayTimeIntervalToNamedTuple(interval); if (ARROW_PREDICT_FALSE(tuple == nullptr)) { @@ -742,10 +739,8 @@ Result MonthDayNanoIntervalArrayToPyList( OwnedRef out_list(PyList_New(array.length())); RETURN_IF_PYERROR(); PyListAssigner out_objects(out_list.obj()); - auto& interval_array = - arrow::internal::checked_cast(array); RETURN_NOT_OK(internal::WriteArrayObjects( - interval_array, + array, [&](const MonthDayNanoIntervalType::MonthDayNanos& interval, PyListAssigner& out) { PyObject* tuple = internal::MonthDayNanoIntervalToNamedTuple(interval); if (ARROW_PREDICT_FALSE(tuple == nullptr)) { From 4ea782a03488e8a186024c35fe69544b0cba8fb0 Mon Sep 17 00:00:00 2001 From: AlenkaF Date: Wed, 2 Dec 2026 13:09:50 +0100 Subject: [PATCH 11/18] Update TypesEnum docstrings --- python/pyarrow/types.py | 2 -- 1 file changed, 2 deletions(-) diff --git a/python/pyarrow/types.py b/python/pyarrow/types.py index 3feb9ce3b413..adad86adee62 100644 --- a/python/pyarrow/types.py +++ b/python/pyarrow/types.py @@ -50,8 +50,6 @@ class TypesEnum(IntEnum): """ An Enum that maps constant values to data types. Exposes the underlying data types representation for type checking purposes. - Note that some of the types listed here are not supported by PyArrow yet: - INTERVAL_MONTHS and INTERVAL_DAY_TIME. Examples -------- From aa79a7396911fdfee64d16ea5b7dbe6b60a3d9ad Mon Sep 17 00:00:00 2001 From: AlenkaF Date: Wed, 2 Dec 2026 13:15:11 +0100 Subject: [PATCH 12/18] Simplify Cython declarations to pass --- python/pyarrow/includes/libarrow.pxd | 8 ++------ 1 file changed, 2 insertions(+), 6 deletions(-) diff --git a/python/pyarrow/includes/libarrow.pxd b/python/pyarrow/includes/libarrow.pxd index 7759c8342997..1ebb86bea875 100644 --- a/python/pyarrow/includes/libarrow.pxd +++ b/python/pyarrow/includes/libarrow.pxd @@ -1387,15 +1387,11 @@ cdef extern from "arrow/api.h" namespace "arrow" nogil: cdef cppclass CMonthIntervalScalar \ "arrow::MonthIntervalScalar"(CScalar): - int32_t value - - cdef cppclass CDayMilliseconds" arrow::DayTimeIntervalType::DayMilliseconds": - int32_t days - int32_t milliseconds + pass cdef cppclass CDayTimeIntervalScalar \ "arrow::DayTimeIntervalScalar"(CScalar): - CDayMilliseconds value + pass cdef cppclass CMonthDayNanoIntervalScalar \ "arrow::MonthDayNanoIntervalScalar"(CScalar): From 10aecdae5301723628b8b349fb7e7dd86fd2711a Mon Sep 17 00:00:00 2001 From: AlenkaF Date: Wed, 2 Dec 2026 13:17:42 +0100 Subject: [PATCH 13/18] Fix ordering of imports --- python/pyarrow-stubs/__init__.pyi | 14 +++++++------- python/pyarrow-stubs/__lib/scalar.pyi | 2 +- python/pyarrow-stubs/__lib/types.pyi | 4 ++-- python/pyarrow-stubs/types.pyi | 4 ++-- 4 files changed, 12 insertions(+), 12 deletions(-) diff --git a/python/pyarrow-stubs/__init__.pyi b/python/pyarrow-stubs/__init__.pyi index 0e2f71005803..5f34a72a63a6 100644 --- a/python/pyarrow-stubs/__init__.pyi +++ b/python/pyarrow-stubs/__init__.pyi @@ -51,6 +51,9 @@ from pyarrow.lib import ( Date32Scalar as Date32Scalar, Date64Array as Date64Array, Date64Scalar as Date64Scalar, + DayTime as DayTime, + DayTimeIntervalArray as DayTimeIntervalArray, + DayTimeIntervalScalar as DayTimeIntervalScalar, Decimal128Array as Decimal128Array, Decimal128Scalar as Decimal128Scalar, Decimal128Type as Decimal128Type, @@ -129,14 +132,11 @@ from pyarrow.lib import ( MemoryManager as MemoryManager, MemoryPool as MemoryPool, Month as Month, - MonthIntervalArray as MonthIntervalArray, - MonthIntervalScalar as MonthIntervalScalar, - DayTime as DayTime, - DayTimeIntervalArray as DayTimeIntervalArray, - DayTimeIntervalScalar as DayTimeIntervalScalar, MonthDayNano as MonthDayNano, MonthDayNanoIntervalArray as MonthDayNanoIntervalArray, MonthDayNanoIntervalScalar as MonthDayNanoIntervalScalar, + MonthIntervalArray as MonthIntervalArray, + MonthIntervalScalar as MonthIntervalScalar, NA as NA, NullArray as NullArray, NullScalar as NullScalar, @@ -207,6 +207,7 @@ from pyarrow.lib import ( cpp_version_info as cpp_version_info, date32 as date32, date64 as date64, + day_time_interval as day_time_interval, decimal128 as decimal128, decimal256 as decimal256, decimal32 as decimal32, @@ -242,9 +243,8 @@ from pyarrow.lib import ( logging_memory_pool as logging_memory_pool, map_ as map_, mimalloc_memory_pool as mimalloc_memory_pool, - month_interval as month_interval, - day_time_interval as day_time_interval, month_day_nano_interval as month_day_nano_interval, + month_interval as month_interval, null as null, nulls as nulls, opaque as opaque, diff --git a/python/pyarrow-stubs/__lib/scalar.pyi b/python/pyarrow-stubs/__lib/scalar.pyi index 19c0b58d4713..f206434db263 100644 --- a/python/pyarrow-stubs/__lib/scalar.pyi +++ b/python/pyarrow-stubs/__lib/scalar.pyi @@ -30,9 +30,9 @@ from pyarrow.lib import ( Buffer, ChunkedArray, DataType, + DayTime, MemoryPool, Month, - DayTime, MonthDayNano, Tensor, _Weakrefable, diff --git a/python/pyarrow-stubs/__lib/types.pyi b/python/pyarrow-stubs/__lib/types.pyi index cad39f04ef6f..a8648780f1ef 100644 --- a/python/pyarrow-stubs/__lib/types.pyi +++ b/python/pyarrow-stubs/__lib/types.pyi @@ -28,6 +28,7 @@ from pyarrow._stubs_typing import ( BoolType, Date32Type, Date64Type, + DayTimeIntervalType, Float16Type, Float32Type, Float64Type, @@ -38,9 +39,8 @@ from pyarrow._stubs_typing import ( IntegerType, LargeBinaryType, LargeStringType, - MonthIntervalType, - DayTimeIntervalType, MonthDayNanoIntervalType, + MonthIntervalType, NullType, StringType, StringViewType, diff --git a/python/pyarrow-stubs/types.pyi b/python/pyarrow-stubs/types.pyi index c6c9fc4e765e..6107ec6588fe 100644 --- a/python/pyarrow-stubs/types.pyi +++ b/python/pyarrow-stubs/types.pyi @@ -30,6 +30,7 @@ from pyarrow._stubs_typing import ( BoolType, Date32Type, Date64Type, + DayTimeIntervalType, Float16Type, Float32Type, Float64Type, @@ -40,9 +41,8 @@ from pyarrow._stubs_typing import ( IntegerType, LargeBinaryType, LargeStringType, - MonthIntervalType, - DayTimeIntervalType, MonthDayNanoIntervalType, + MonthIntervalType, NullType, StringType, StringViewType, From a563c90fd1853c6c2154ee9e433d9c101f2c005d Mon Sep 17 00:00:00 2001 From: AlenkaF Date: Wed, 2 Dec 2026 13:24:19 +0100 Subject: [PATCH 14/18] Add moe tests - negative intervals, sliced and empty arrays --- python/pyarrow/tests/test_compute.py | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/python/pyarrow/tests/test_compute.py b/python/pyarrow/tests/test_compute.py index c687a708cf5f..0db8fd2c171f 100644 --- a/python/pyarrow/tests/test_compute.py +++ b/python/pyarrow/tests/test_compute.py @@ -4652,6 +4652,11 @@ def test_interval_between(): assert isinstance(result[0], pa.MonthIntervalScalar) assert str(result[0]) == "Month(months=4)" assert result.to_pylist() == [pa.Month([4]), None, pa.Month([1429])] + assert result[1:].to_pylist() == [None, pa.Month([1429])] + assert result[:0].to_pylist() == [] + + result = pc.month_interval_between(arr2, arr1) + assert result.to_pylist() == [pa.Month([-4]), None, pa.Month([-1429])] result = pc.day_time_interval_between(arr1, arr2) assert isinstance(result, pa.DayTimeIntervalArray) @@ -4660,3 +4665,10 @@ def test_interval_between(): assert result.to_pylist() == [pa.DayTime([125, 0]), None, pa.DayTime([43483, 0])] + assert result[1:].to_pylist() == [None, pa.DayTime([43483, 0])] + assert result[:0].to_pylist() == [] + + result = pc.day_time_interval_between(arr2, arr1) + assert result.to_pylist() == [pa.DayTime([-125, 0]), + None, + pa.DayTime([-43483, 0])] From 7053ff97483622047a289d6b0dc0ff09a18b4b87 Mon Sep 17 00:00:00 2001 From: AlenkaF Date: Wed, 2 Dec 2026 13:27:41 +0100 Subject: [PATCH 15/18] Update API reference --- docs/source/python/api/arrays.rst | 9 +++++++++ python/pyarrow/scalar.pxi | 4 ++-- 2 files changed, 11 insertions(+), 2 deletions(-) diff --git a/docs/source/python/api/arrays.rst b/docs/source/python/api/arrays.rst index 66adfa6addd7..4a8c3c7cdb51 100644 --- a/docs/source/python/api/arrays.rst +++ b/docs/source/python/api/arrays.rst @@ -173,3 +173,12 @@ classes may expose data type-specific methods or properties. JsonScalar UuidScalar Bool8Scalar + +The ``as_py()`` methods of the interval scalars return these named tuples: + +.. autosummary:: + :toctree: ../generated/ + + Month + DayTime + MonthDayNano diff --git a/python/pyarrow/scalar.pxi b/python/pyarrow/scalar.pxi index 41d8e8fb831d..b07f6a5e0548 100644 --- a/python/pyarrow/scalar.pxi +++ b/python/pyarrow/scalar.pxi @@ -928,7 +928,7 @@ cdef class MonthIntervalScalar(Scalar): Returns ------- - pyarrow.Month + pyarrow.Month or None """ cdef: PyObject* val @@ -963,7 +963,7 @@ cdef class DayTimeIntervalScalar(Scalar): Returns ------- - pyarrow.DayTime + pyarrow.DayTime or None """ cdef: PyObject* val From fb2d1b6ffc3c5c9f81938e53b6bec7937473a722 Mon Sep 17 00:00:00 2001 From: AlenkaF Date: Wed, 2 Dec 2026 13:29:12 +0100 Subject: [PATCH 16/18] Use Tadeja's extra test example for repr --- python/pyarrow/tests/test_scalars.py | 2 ++ 1 file changed, 2 insertions(+) diff --git a/python/pyarrow/tests/test_scalars.py b/python/pyarrow/tests/test_scalars.py index aa9ca8ad0f79..0998f68de327 100644 --- a/python/pyarrow/tests/test_scalars.py +++ b/python/pyarrow/tests/test_scalars.py @@ -546,6 +546,7 @@ def test_day_time_and_month_interval(): assert arr[0].value == arr[0].as_py() assert arr[1].as_py(maps_as_pydicts="strict") is None assert arr[1].value is None + assert repr(arr[1]) == "" arr = pc.day_time_interval_between(arr1, arr2) assert isinstance(arr[0].as_py(), pa.DayTime) @@ -555,6 +556,7 @@ def test_day_time_and_month_interval(): assert arr[0].value == arr[0].as_py() assert arr[1].as_py(maps_as_pydicts="strict") is None assert arr[1].value is None + assert repr(arr[1]) == "" def test_month_day_nano_interval(): From 52ab34ca60ad5bf0ef48d9f7cecc4f9bf0e12b80 Mon Sep 17 00:00:00 2001 From: Alenka Frim Date: Wed, 2 Dec 2026 14:37:39 +0100 Subject: [PATCH 17/18] Apply batched suggestions from code review Co-authored-by: tadeja --- python/pyarrow/src/arrow/python/datetime.cc | 4 ++-- python/pyarrow/src/arrow/python/datetime.h | 4 ++-- python/pyarrow/types.pxi | 4 ++-- 3 files changed, 6 insertions(+), 6 deletions(-) diff --git a/python/pyarrow/src/arrow/python/datetime.cc b/python/pyarrow/src/arrow/python/datetime.cc index c63f7e9e89de..156e266bde93 100644 --- a/python/pyarrow/src/arrow/python/datetime.cc +++ b/python/pyarrow/src/arrow/python/datetime.cc @@ -64,7 +64,7 @@ static PyStructSequence_Desc MonthTupleDesc = { static PyTypeObject DayTimeTupleType = {}; static PyStructSequence_Field DayTimeField[] = { - {"days", "The number days in the interval"}, + {"days", "The number of days in the interval"}, {"milliseconds", "The number of milliseconds in the interval"}, {nullptr, nullptr}}; @@ -76,7 +76,7 @@ static PyTypeObject MonthDayNanoTupleType = {}; static PyStructSequence_Field MonthDayNanoField[] = { {"months", "The number of months in the interval"}, - {"days", "The number days in the interval"}, + {"days", "The number of days in the interval"}, {"nanoseconds", "The number of nanoseconds in the interval"}, {nullptr, nullptr}}; diff --git a/python/pyarrow/src/arrow/python/datetime.h b/python/pyarrow/src/arrow/python/datetime.h index 1569ab1afb52..a44f847882eb 100644 --- a/python/pyarrow/src/arrow/python/datetime.h +++ b/python/pyarrow/src/arrow/python/datetime.h @@ -223,7 +223,7 @@ ARROW_PYTHON_EXPORT Result MonthIntervalArrayToPyList(const MonthIntervalArray& array); /// \brief Convert the Scalar object to a pyarrow.Month (or None if -/// is isn't valid). +/// it isn't valid). ARROW_PYTHON_EXPORT Result MonthIntervalScalarToPyObject(const MonthIntervalScalar& scalar); @@ -243,7 +243,7 @@ ARROW_PYTHON_EXPORT Result DayTimeIntervalArrayToPyList(const DayTimeIntervalArray& array); /// \brief Convert the Scalar object to a pyarrow.DayTime (or None if -/// is isn't valid). +/// it isn't valid). ARROW_PYTHON_EXPORT Result DayTimeIntervalScalarToPyObject(const DayTimeIntervalScalar& scalar); diff --git a/python/pyarrow/types.pxi b/python/pyarrow/types.pxi index ef326d7329ce..13d49e90b66a 100644 --- a/python/pyarrow/types.pxi +++ b/python/pyarrow/types.pxi @@ -4357,7 +4357,7 @@ def month_interval(): Examples -------- - Create an instance of an month_interval type: + Create an instance of a month_interval type: >>> import pyarrow as pa >>> pa.month_interval() @@ -4395,7 +4395,7 @@ def day_time_interval(): Examples -------- - Create an instance of an day_time_interval type: + Create an instance of a day_time_interval type: >>> import pyarrow as pa >>> pa.day_time_interval() From b2856c8e50ba5248813bfffc49842afd95991318 Mon Sep 17 00:00:00 2001 From: AlenkaF Date: Wed, 2 Dec 2026 14:40:14 +0100 Subject: [PATCH 18/18] Two more typos --- python/pyarrow/src/arrow/python/datetime.h | 2 +- python/pyarrow/types.pxi | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/python/pyarrow/src/arrow/python/datetime.h b/python/pyarrow/src/arrow/python/datetime.h index a44f847882eb..d4bfdc6c5fb3 100644 --- a/python/pyarrow/src/arrow/python/datetime.h +++ b/python/pyarrow/src/arrow/python/datetime.h @@ -265,7 +265,7 @@ Result MonthDayNanoIntervalArrayToPyList( const MonthDayNanoIntervalArray& array); /// \brief Convert the Scalar object to a pyarrow.MonthDayNano (or None if -/// is isn't valid). +/// it isn't valid). ARROW_PYTHON_EXPORT Result MonthDayNanoIntervalScalarToPyObject( const MonthDayNanoIntervalScalar& scalar); diff --git a/python/pyarrow/types.pxi b/python/pyarrow/types.pxi index 13d49e90b66a..0d7e86701260 100644 --- a/python/pyarrow/types.pxi +++ b/python/pyarrow/types.pxi @@ -4432,7 +4432,7 @@ def month_day_nano_interval(): Examples -------- - Create an instance of an month_day_nano_interval type: + Create an instance of a month_day_nano_interval type: >>> import pyarrow as pa >>> pa.month_day_nano_interval()