diff --git a/docs/source/python/api/arrays.rst b/docs/source/python/api/arrays.rst index 290ce09befb1..4a8c3c7cdb51 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 @@ -169,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/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-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..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, @@ -128,9 +131,12 @@ from pyarrow.lib import ( MapType as MapType, MemoryManager as MemoryManager, MemoryPool as MemoryPool, + Month as Month, MonthDayNano as MonthDayNano, MonthDayNanoIntervalArray as MonthDayNanoIntervalArray, MonthDayNanoIntervalScalar as MonthDayNanoIntervalScalar, + MonthIntervalArray as MonthIntervalArray, + MonthIntervalScalar as MonthIntervalScalar, NA as NA, NullArray as NullArray, NullScalar as NullScalar, @@ -201,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, @@ -237,6 +244,7 @@ from pyarrow.lib import ( map_ as map_, mimalloc_memory_pool as mimalloc_memory_pool, 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/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..f206434db263 100644 --- a/python/pyarrow-stubs/__lib/scalar.pyi +++ b/python/pyarrow-stubs/__lib/scalar.pyi @@ -30,7 +30,9 @@ from pyarrow.lib import ( Buffer, ChunkedArray, DataType, + DayTime, MemoryPool, + Month, 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..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, @@ -39,6 +40,7 @@ from pyarrow._stubs_typing import ( LargeBinaryType, LargeStringType, MonthDayNanoIntervalType, + MonthIntervalType, NullType, StringType, StringViewType, @@ -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..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, @@ -41,6 +42,7 @@ from pyarrow._stubs_typing import ( LargeBinaryType, LargeStringType, MonthDayNanoIntervalType, + MonthIntervalType, NullType, StringType, StringViewType, @@ -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/__init__.py b/python/pyarrow/__init__.py index c024cdc69a7d..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) @@ -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..ac3b87334638 100644 --- a/python/pyarrow/array.pxi +++ b/python/pyarrow/array.pxi @@ -2717,6 +2717,70 @@ cdef class DurationArray(NumericArray): """ +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 + """ + self._assert_cpu() + 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 + """ + self._assert_cpu() + 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): """ Concrete class for Arrow arrays of interval[MonthDayNano] type. @@ -2738,6 +2802,7 @@ cdef class MonthDayNanoIntervalArray(Array): ------- lst : list """ + self._assert_cpu() cdef: CResult[PyObject*] maybe_py_list PyObject* py_list @@ -5316,6 +5381,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..1ebb86bea875 100644 --- a/python/pyarrow/includes/libarrow.pxd +++ b/python/pyarrow/includes/libarrow.pxd @@ -146,9 +146,9 @@ 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_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_INTERVAL_DAY_TIME" arrow::Type::INTERVAL_DAY_TIME" + _Type_INTERVAL_MONTH_DAY_NANO" arrow::Type::INTERVAL_MONTH_DAY_NANO" _Type_BINARY" arrow::Type::BINARY" _Type_STRING" arrow::Type::STRING" @@ -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 @@ -1377,6 +1385,14 @@ cdef extern from "arrow/api.h" namespace "arrow" nogil: cdef cppclass CDurationScalar" arrow::DurationScalar"(CScalar): int64_t value + cdef cppclass CMonthIntervalScalar \ + "arrow::MonthIntervalScalar"(CScalar): + pass + + cdef cppclass CDayTimeIntervalScalar \ + "arrow::DayTimeIntervalScalar"(CScalar): + pass + cdef cppclass CMonthDayNanoIntervalScalar \ "arrow::MonthDayNanoIntervalScalar"(CScalar): 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.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..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() @@ -130,6 +132,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 @@ -149,8 +153,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 diff --git a/python/pyarrow/scalar.pxi b/python/pyarrow/scalar.pxi index 8c9adf9b522c..b07f6a5e0548 100644 --- a/python/pyarrow/scalar.pxi +++ b/python/pyarrow/scalar.pxi @@ -904,6 +904,76 @@ cdef class DurationScalar(Scalar): return datetime.timedelta(microseconds=sp.value // 1000) +cdef class MonthIntervalScalar(Scalar): + """ + Concrete class for month interval scalars. + """ + + @property + def value(self): + """ + Same as self.as_py() + """ + return self.as_py() + + def as_py(self, *, maps_as_pydicts=None): + """ + Return this value as a pyarrow.Month. + + Parameters + ---------- + maps_as_pydicts : str, optional, default `None` + Valid values are `None`, 'lossy', or 'strict'. + This parameter is ignored for non-nested Scalars. + + Returns + ------- + pyarrow.Month or None + """ + cdef: + PyObject* val + CMonthIntervalScalar* scalar + scalar = self.wrapped.get() + val = GetResultValue(MonthIntervalScalarToPyObject( + deref(scalar))) + return PyObject_to_object(val) + + +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 as_py(self, *, maps_as_pydicts=None): + """ + Return this value as a pyarrow.DayTime. + + Parameters + ---------- + maps_as_pydicts : str, optional, default `None` + Valid values are `None`, 'lossy', or 'strict'. + This parameter is ignored for non-nested Scalars. + + Returns + ------- + pyarrow.DayTime or None + """ + cdef: + PyObject* val + CDayTimeIntervalScalar* scalar + scalar = self.wrapped.get() + val = GetResultValue(DayTimeIntervalScalarToPyObject( + deref(scalar))) + return PyObject_to_object(val) + + cdef class MonthDayNanoIntervalScalar(Scalar): """ Concrete class for month, day, nanosecond interval scalars. @@ -1681,6 +1751,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/datetime.cc b/python/pyarrow/src/arrow/python/datetime.cc index 6a835c2d37ce..156e266bde93 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 of 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 of 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,15 +696,51 @@ struct PyListAssigner { } // namespace +Result MonthIntervalArrayToPyList(const MonthIntervalArray& array) { + OwnedRef out_list(PyList_New(array.length())); + RETURN_IF_PYERROR(); + PyListAssigner out_objects(out_list.obj()); + RETURN_NOT_OK(internal::WriteArrayObjects( + 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()); + RETURN_NOT_OK(internal::WriteArrayObjects( + 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())); 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)) { @@ -664,6 +754,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..d4bfdc6c5fb3 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 +/// it 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 +/// it 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 @@ -221,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/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..0db8fd2c171f 100644 --- a/python/pyarrow/tests/test_compute.py +++ b/python/pyarrow/tests/test_compute.py @@ -4631,3 +4631,44 @@ 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]) == "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) + assert isinstance(result[0], pa.DayTimeIntervalScalar) + assert str(result[0]) == "DayTime(days=125, milliseconds=0)" + 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])] 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_scalars.py b/python/pyarrow/tests/test_scalars.py index 533a05850522..0998f68de327 100644 --- a/python/pyarrow/tests/test_scalars.py +++ b/python/pyarrow/tests/test_scalars.py @@ -529,6 +529,36 @@ 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(), 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 + assert repr(arr[1]) == "" + + 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 + assert repr(arr[1]) == "" + + def test_month_day_nano_interval(): triple = pa.MonthDayNano([-3600, 1800, -50]) arr = pa.array([triple]) 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()), ] 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..0d7e86701260 100644 --- a/python/pyarrow/types.pxi +++ b/python/pyarrow/types.pxi @@ -4350,6 +4350,81 @@ def duration(unit): return out +def month_interval(): + """ + Create instance of an interval type representing months + between two dates. + + Examples + -------- + Create an instance of a 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 a 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) + + def month_day_nano_interval(): """ Create instance of an interval type representing months, days and @@ -4357,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() @@ -5779,6 +5854,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..adad86adee62 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) @@ -49,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 -------- @@ -395,7 +394,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")