From 9dd1ecae801dc639e33f86f1bee99d1a78371491 Mon Sep 17 00:00:00 2001 From: Ahmed Abualsaud Date: Fri, 20 Nov 2026 16:56:00 -0800 Subject: [PATCH 1/2] Make DateTime a portable logical type with a precision Java's DateTime now takes a precision (0 to 9, default 6) and is the standard beam:logical_type:datetime:v1 type, so SqlTypes.DATETIME is DateTime(6). Python gets a matching apache_beam.utils.timestamp.DateTime that converts to and from datetime.datetime and Arrow timestamps. --- CHANGES.md | 2 + .../model/fnexecution/v1/standard_coders.yaml | 32 +++ .../beam/model/pipeline/v1/schema.proto | 10 + .../regression/coders/fromyaml/fromyaml.go | 1 + .../beam/sdk/schemas/SchemaTranslation.java | 2 + .../sdk/schemas/logicaltypes/DateTime.java | 83 ++++++- .../sdk/schemas/SchemaTranslationTest.java | 2 + .../logicaltypes/LogicalTypesTest.java | 39 ++++ .../apache_beam/coders/row_coder_test.py | 54 +++++ .../apache_beam/portability/common_urns.py | 1 + .../transforms/managed_iceberg_it_test.py | 6 +- sdks/python/apache_beam/typehints/schemas.py | 83 +++++++ .../apache_beam/typehints/schemas_test.py | 84 +++++++ sdks/python/apache_beam/utils/timestamp.py | 213 ++++++++++++++++++ .../apache_beam/utils/timestamp_test.py | 139 ++++++++++++ 15 files changed, 739 insertions(+), 12 deletions(-) diff --git a/CHANGES.md b/CHANGES.md index b7228eadb5ae..c08c42a5ee3f 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -111,6 +111,7 @@ * [Beam SQL] Added a live view to the SQL shell. A streaming (unbounded) SELECT shows its rows as they arrive, with an `op` column for each row's change kind ([#41313](https://github.com/apache/beam/issues/41313)). * (Python) `BatchElements` can group elements by key across workers (`key_fn`, `num_shards`), and RunInference model handlers can use it through `batch_key_fn` / `batch_key_num_shards`. `apache_beam.ml.inference.prefix_batching` adds a `PrefixBatchingConfig` and prompt/chat prefix extractors so LLM handlers can batch requests that share a prompt prefix and hit the server's prefix cache ([#40905](https://github.com/apache/beam/pull/40905)). * (Go) Added pass-through registration for fixed and variable length string and bytes logical types ([#39684](https://github.com/apache/beam/issues/39684)). +* (Java/Python) Added DateTime as a new portable logical type (`datetime:v1`). Java `DateTime` takes a precision (`DateTime.of(p)`, `MILLIS`, `MICROS`, `NANOS`), which defaults to 6. Python maps it to the new `apache_beam.utils.timestamp.DateTime`. ### Performance @@ -128,6 +129,7 @@ [comment]: # "generic breaking changes if not covered in following sections." * (Java) Flink runner: batch pipelines now assign source splits to readers statically by default instead of lazily. Set `--sourceStaticSplitThresholdMb=0` to restore lazy assignment ([#40607](https://github.com/apache/beam/issues/40607)). +* (Java) `SqlTypes.DATETIME` is now `DateTime` with precision 6, so a `LocalDateTime` with digits below a microsecond throws instead of being stored. Use `DateTime.NANOS` for those values. * X behavior was changed ([#X](https://github.com/apache/beam/issues/X)). ### Package upgrades diff --git a/model/fn-execution/src/main/resources/org/apache/beam/model/fnexecution/v1/standard_coders.yaml b/model/fn-execution/src/main/resources/org/apache/beam/model/fnexecution/v1/standard_coders.yaml index eb7999680074..9f947e4761a0 100644 --- a/model/fn-execution/src/main/resources/org/apache/beam/model/fnexecution/v1/standard_coders.yaml +++ b/model/fn-execution/src/main/resources/org/apache/beam/model/fnexecution/v1/standard_coders.yaml @@ -657,3 +657,35 @@ coder: examples: "\x01\x00\x02\x00\xb6\x95\xd5\xf9\x05\x95\x9a\xef:": {f_timestamp: {seconds: 1597328054, subseconds: 123456789}} "\x01\x00\x02\x00\xfe\xff\xff\xff\xff\xff\xff\xff\xff\x01\xff\x93\xeb\xdc\x03": {f_timestamp: {seconds: -2, subseconds: 999999999}} + +--- + +coder: + urn: "beam:coder:row:v1" + # f_datetime: logical(datetime:v1, precision=3, representation row) + payload: "\x0a}\x0a\x0af_datetime\x1ao:m\x0a\x1dbeam:logical_type:datetime:v1\x1aB2@\x0a>\x0a\x0a\x0a\x04Date\x1a\x02\x10\x04\x0a\x0a\x0a\x04Time\x1a\x02\x10\x04\x12$83a4147a-2f70-4c01-bb68-1e864ad6990c\"\x02\x10\x03*\x04\x0a\x02\x18\x03\x12$4fc4774e-37df-400a-8f31-7ef2a0dff64d" +examples: + "\x01\x00\x02\x00\xb7\x90\x01\xc0\xe1\xad\xbe\xd8\xd3\x0b": {f_datetime: {Date: 18487, Time: 51254123000000}} + "\x01\x00\x02\x00\xff\xff\xff\xff\xff\xff\xff\xff\xff\x01\xc0\xfb\xfe\x89\xc9\xd2\x13": {f_datetime: {Date: -1, Time: 86399999000000}} + +--- + +coder: + urn: "beam:coder:row:v1" + # f_datetime: logical(datetime:v1, precision=6, representation row) + payload: "\x0a}\x0a\x0af_datetime\x1ao:m\x0a\x1dbeam:logical_type:datetime:v1\x1aB2@\x0a>\x0a\x0a\x0a\x04Date\x1a\x02\x10\x04\x0a\x0a\x0a\x04Time\x1a\x02\x10\x04\x12$2b59abb6-4d5c-46e5-8ba7-7bac2152e710\"\x02\x10\x03*\x04\x0a\x02\x18\x06\x12$9a6dd2eb-068c-48c4-bd35-08dda524b154" +examples: + "\x01\x00\x02\x00\xb7\x90\x01\x80\xcc\xc9\xbe\xd8\xd3\x0b": {f_datetime: {Date: 18487, Time: 51254123456000}} + "\x01\x00\x02\x00\xff\xff\xff\xff\xff\xff\xff\xff\xff\x01\x98\xf8\xbb\x8a\xc9\xd2\x13": {f_datetime: {Date: -1, Time: 86399999999000}} + "\x01\x00\x02\x00\xc6\x8d\xd4\xff\xff\xff\xff\xff\xff\x01\x00": {f_datetime: {Date: -719162, Time: 0}} + "\x01\x00\x02\x00\xa0\x81\xb3\x01\x98\xf8\xbb\x8a\xc9\xd2\x13": {f_datetime: {Date: 2932896, Time: 86399999999000}} + +--- + +coder: + urn: "beam:coder:row:v1" + # f_datetime: logical(datetime:v1, precision=9, representation row) + payload: "\x0a}\x0a\x0af_datetime\x1ao:m\x0a\x1dbeam:logical_type:datetime:v1\x1aB2@\x0a>\x0a\x0a\x0a\x04Date\x1a\x02\x10\x04\x0a\x0a\x0a\x04Time\x1a\x02\x10\x04\x12$50fa1e41-87ca-49c2-bbf9-2213fda455df\"\x02\x10\x03*\x04\x0a\x02\x18\x09\x12$2528740c-f08c-4259-af4b-4feb13ff0d07" +examples: + "\x01\x00\x02\x00\xb7\x90\x01\x95\xd2\xc9\xbe\xd8\xd3\x0b": {f_datetime: {Date: 18487, Time: 51254123456789}} + "\x01\x00\x02\x00\xff\xff\xff\xff\xff\xff\xff\xff\xff\x01\xff\xff\xbb\x8a\xc9\xd2\x13": {f_datetime: {Date: -1, Time: 86399999999999}} diff --git a/model/pipeline/src/main/proto/org/apache/beam/model/pipeline/v1/schema.proto b/model/pipeline/src/main/proto/org/apache/beam/model/pipeline/v1/schema.proto index c114c35f2d90..d5ec03d52e0d 100644 --- a/model/pipeline/src/main/proto/org/apache/beam/model/pipeline/v1/schema.proto +++ b/model/pipeline/src/main/proto/org/apache/beam/model/pipeline/v1/schema.proto @@ -247,6 +247,16 @@ message LogicalTypes { // e.g. -1.5s at precision 6 is {seconds: -2, subseconds: 500000}. TIMESTAMP = 9 [(org.apache.beam.model.pipeline.v1.beam_urn) = "beam:logical_type:timestamp:v1"]; + + // A URN for DateTime type + // - Representation type: ROW + // - Argument type: INT32, the precision, which defaults to 6. + // A date and wall-clock time without a timezone. Date counts days + // since the epoch, and Time counts nanoseconds since midnight at every + // precision. The precision is the number of decimal digits of the + // fraction of a second, and every finer digit is zero. + DATETIME = 10 [(org.apache.beam.model.pipeline.v1.beam_urn) = + "beam:logical_type:datetime:v1"]; } } diff --git a/sdks/go/test/regression/coders/fromyaml/fromyaml.go b/sdks/go/test/regression/coders/fromyaml/fromyaml.go index d3282c40d27f..2571c642959f 100644 --- a/sdks/go/test/regression/coders/fromyaml/fromyaml.go +++ b/sdks/go/test/regression/coders/fromyaml/fromyaml.go @@ -54,6 +54,7 @@ var unimplementedCoders = map[string]bool{ var filteredCases = []struct{ filter, reason string }{ {"30ea5a25-dcd8-4cdb-abeb-5332d15ab4b9", "https://github.com/apache/beam/issues/21206: Support encoding position."}, {"beam:logical_type:timestamp:v1", "https://github.com/apache/beam/issues/39684: Support timestamp."}, + {"beam:logical_type:datetime:v1", "https://github.com/apache/beam/issues/39684: Support datetime."}, } // Coder is a representation a serialized beam coder. diff --git a/sdks/java/core/src/main/java/org/apache/beam/sdk/schemas/SchemaTranslation.java b/sdks/java/core/src/main/java/org/apache/beam/sdk/schemas/SchemaTranslation.java index 8122704e6436..bfc04883e582 100644 --- a/sdks/java/core/src/main/java/org/apache/beam/sdk/schemas/SchemaTranslation.java +++ b/sdks/java/core/src/main/java/org/apache/beam/sdk/schemas/SchemaTranslation.java @@ -44,6 +44,7 @@ import org.apache.beam.sdk.schemas.Schema.LogicalType; import org.apache.beam.sdk.schemas.Schema.TypeName; import org.apache.beam.sdk.schemas.logicaltypes.Date; +import org.apache.beam.sdk.schemas.logicaltypes.DateTime; import org.apache.beam.sdk.schemas.logicaltypes.FixedBytes; import org.apache.beam.sdk.schemas.logicaltypes.FixedPrecisionNumeric; import org.apache.beam.sdk.schemas.logicaltypes.FixedString; @@ -117,6 +118,7 @@ private static String getLogicalTypeUrn(String identifier) { .put(VariableString.IDENTIFIER, VariableString.class) .put(Date.IDENTIFIER, Date.class) .put(Timestamp.IDENTIFIER, Timestamp.class) + .put(DateTime.IDENTIFIER, DateTime.class) .build(); public static SchemaApi.Schema schemaToProto(Schema schema, boolean serializeLogicalType) { diff --git a/sdks/java/core/src/main/java/org/apache/beam/sdk/schemas/logicaltypes/DateTime.java b/sdks/java/core/src/main/java/org/apache/beam/sdk/schemas/logicaltypes/DateTime.java index 2659fc8644a7..ea052de9972d 100644 --- a/sdks/java/core/src/main/java/org/apache/beam/sdk/schemas/logicaltypes/DateTime.java +++ b/sdks/java/core/src/main/java/org/apache/beam/sdk/schemas/logicaltypes/DateTime.java @@ -18,10 +18,14 @@ package org.apache.beam.sdk.schemas.logicaltypes; import static org.apache.beam.sdk.util.Preconditions.checkArgumentNotNull; +import static org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.base.Preconditions.checkArgument; +import static org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.base.Preconditions.checkState; import java.time.LocalDate; import java.time.LocalDateTime; import java.time.LocalTime; +import org.apache.beam.model.pipeline.v1.RunnerApi; +import org.apache.beam.model.pipeline.v1.SchemaApi; import org.apache.beam.sdk.schemas.Schema; import org.apache.beam.sdk.values.Row; @@ -36,29 +40,72 @@ * that represents incrementing count of days where day 0 is 1970-01-01 (ISO). Time field is the * same as the base type of {@link Time}, which is a Long that represents a count of time in * nanoseconds. + * + *

The precision is the number of digits in the fraction of a second, from 0 to 9, and defaults + * to 6. {@link #toBaseType} refuses a value with finer digits. */ public class DateTime implements Schema.LogicalType { - public static final String IDENTIFIER = "beam:logical_type:datetime:v1"; + // The UID from before DateTime had a precision, so instances that earlier versions serialized + // still deserialize. + private static final long serialVersionUID = -3033263475478247643L; + + public static final String IDENTIFIER = + SchemaApi.LogicalTypes.Enum.DATETIME + .getValueDescriptor() + .getOptions() + .getExtension(RunnerApi.beamUrn); public static final String DATE_FIELD_NAME = "Date"; public static final String TIME_FIELD_NAME = "Time"; public static final Schema DATETIME_SCHEMA = Schema.builder().addInt64Field(DATE_FIELD_NAME).addInt64Field(TIME_FIELD_NAME).build(); + static final int MAX_PRECISION = 9; + static final int DEFAULT_PRECISION = 6; + + public static final DateTime MILLIS = DateTime.of(3); + public static final DateTime MICROS = DateTime.of(6); + public static final DateTime NANOS = DateTime.of(9); + + private final int precision; + private final int scalingFactor; + + /** A DateTime with the default precision, 6. */ + public DateTime() { + this(DEFAULT_PRECISION); + } + + private DateTime(int precision) { + checkArgument( + precision >= 0 && precision <= MAX_PRECISION, + "DateTime precision must be between 0 and %s (inclusive), but was %s.", + MAX_PRECISION, + precision); + this.precision = precision; + this.scalingFactor = (int) Math.pow(10, MAX_PRECISION - precision); + } + + public static DateTime of(int precision) { + return new DateTime(precision); + } + + // Instances that earlier versions serialized have neither field set, and they meant micros. + private Object readResolve() { + return scalingFactor == 0 ? MICROS : this; + } + @Override public String getIdentifier() { return IDENTIFIER; } - // unused @Override public Schema.FieldType getArgumentType() { - return Schema.FieldType.STRING; + return Schema.FieldType.INT32; } - // unused @Override - public String getArgument() { - return ""; + public Integer getArgument() { + return precision; } @Override @@ -68,21 +115,35 @@ public Schema.FieldType getBaseType() { @Override public Row toBaseType(LocalDateTime input) { + long nanoOfDay = input.toLocalTime().toNanoOfDay(); + checkState( + nanoOfDay % scalingFactor == 0, + "DateTime logical type was configured with precision %s, but encountered %s, which has " + + "finer digits.", + precision, + input); return Row.withSchema(DATETIME_SCHEMA) - .addValues(input.toLocalDate().toEpochDay(), input.toLocalTime().toNanoOfDay()) + .addValues(input.toLocalDate().toEpochDay(), nanoOfDay) .build(); } @Override public LocalDateTime toInputType(Row base) { + long nanoOfDay = + checkArgumentNotNull( + base.getInt64(TIME_FIELD_NAME), + "While trying to convert to LocalDateTime: Row missing time field"); + checkArgument( + nanoOfDay % scalingFactor == 0, + "While trying to convert to LocalDateTime: time field %s has digits finer than precision " + + "%s. This likely indicates data corruption or a precision mismatch.", + nanoOfDay, + precision); return LocalDateTime.of( LocalDate.ofEpochDay( checkArgumentNotNull( base.getInt64(DATE_FIELD_NAME), "While trying to convert to LocalDateTime: Row missing date field")), - LocalTime.ofNanoOfDay( - checkArgumentNotNull( - base.getInt64(TIME_FIELD_NAME), - "While trying to convert to LocalDateTime: Row missing time field"))); + LocalTime.ofNanoOfDay(nanoOfDay)); } } diff --git a/sdks/java/core/src/test/java/org/apache/beam/sdk/schemas/SchemaTranslationTest.java b/sdks/java/core/src/test/java/org/apache/beam/sdk/schemas/SchemaTranslationTest.java index 925b1e02b786..43986d2e9e2f 100644 --- a/sdks/java/core/src/test/java/org/apache/beam/sdk/schemas/SchemaTranslationTest.java +++ b/sdks/java/core/src/test/java/org/apache/beam/sdk/schemas/SchemaTranslationTest.java @@ -467,6 +467,8 @@ public static Iterable data() { // INT16/INT32 subseconds representation boundary. .add(FieldType.logicalType(Timestamp.of(4))) .add(FieldType.logicalType(Timestamp.of(5))) + .add(FieldType.logicalType(DateTime.MILLIS)) + .add(FieldType.logicalType(DateTime.NANOS)) .add(FieldType.logicalType(new PortableNullArgLogicalType())) .add(FieldType.logicalType(new NullArgumentLogicalType())) .build(); diff --git a/sdks/java/core/src/test/java/org/apache/beam/sdk/schemas/logicaltypes/LogicalTypesTest.java b/sdks/java/core/src/test/java/org/apache/beam/sdk/schemas/logicaltypes/LogicalTypesTest.java index 1db7c2c59310..c98e2df20f79 100644 --- a/sdks/java/core/src/test/java/org/apache/beam/sdk/schemas/logicaltypes/LogicalTypesTest.java +++ b/sdks/java/core/src/test/java/org/apache/beam/sdk/schemas/logicaltypes/LogicalTypesTest.java @@ -21,9 +21,13 @@ import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertThrows; +import java.io.ByteArrayInputStream; +import java.io.ObjectInputStream; import java.math.BigDecimal; import java.time.Duration; import java.time.Instant; +import java.time.LocalDateTime; +import java.util.Base64; import java.util.Map; import java.util.UUID; import org.apache.beam.sdk.schemas.Schema; @@ -508,4 +512,39 @@ public void testTimestampExtremeValues() { Row maxRow = Row.withSchema(schema).addValue(nearMax).build(); assertEquals(nearMax, maxRow.getLogicalTypeValue(0, Instant.class)); } + + @Test + public void testDateTimePrecision() { + LocalDateTime nanos = LocalDateTime.of(2020, 8, 13, 14, 14, 14, 123_456_789); + assertEquals(nanos, DateTime.NANOS.toInputType(DateTime.NANOS.toBaseType(nanos))); + // SqlTypes.DATETIME is micros, so it refuses finer digits, as Timestamp does. + assertEquals(6, (int) SqlTypes.DATETIME.getArgument()); + assertThrows(IllegalStateException.class, () -> SqlTypes.DATETIME.toBaseType(nanos)); + Row micros = SqlTypes.DATETIME.toBaseType(nanos.withNano(123_456_000)); + assertEquals(51_254_123_456_000L, (long) micros.getInt64(DateTime.TIME_FIELD_NAME)); + // Finer digits arriving to decode mean corrupt data. + Row corrupt = + Row.withSchema(DateTime.DATETIME_SCHEMA).addValues(18487L, 51_254_123_456_001L).build(); + assertThrows(IllegalArgumentException.class, () -> SqlTypes.DATETIME.toInputType(corrupt)); + assertThrows(IllegalArgumentException.class, () -> DateTime.of(10)); + assertThrows(IllegalArgumentException.class, () -> DateTime.of(-1)); + } + + @Test + public void testDateTimeReadsPreviouslySerializedForm() throws Exception { + // A DateTime that Beam 2.77 Java-serialized, before DateTime had a precision. Flink savepoints + // and serialized coders hold this form. + byte[] serialized = + Base64.getDecoder() + .decode( + "rO0ABXNyADFvcmcuYXBhY2hlLmJlYW0uc2RrLnNjaGVtYXMubG9naWNhbHR5cGVzLkRhdGVUaW1l" + + "1eeu8KHzxyUCAAB4cA=="); + DateTime dateTime; + try (ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(serialized))) { + dateTime = (DateTime) in.readObject(); + } + assertEquals(6, (int) dateTime.getArgument()); + LocalDateTime micros = LocalDateTime.of(2020, 8, 13, 14, 14, 14, 123_456_000); + assertEquals(micros, dateTime.toInputType(dateTime.toBaseType(micros))); + } } diff --git a/sdks/python/apache_beam/coders/row_coder_test.py b/sdks/python/apache_beam/coders/row_coder_test.py index 9bc6b23356b8..6bf85db01af8 100644 --- a/sdks/python/apache_beam/coders/row_coder_test.py +++ b/sdks/python/apache_beam/coders/row_coder_test.py @@ -37,6 +37,7 @@ from apache_beam.typehints.schemas import _static_encoding_option_pb2 from apache_beam.typehints.schemas import named_tuple_from_schema from apache_beam.typehints.schemas import typing_to_runner_api +from apache_beam.utils.timestamp import DateTime from apache_beam.utils.timestamp import Timestamp Person = typing.NamedTuple( @@ -259,6 +260,59 @@ def test_create_row_coder_from_schema_with_parameterized_timestamp(self): self.assertEqual(test_case, decoded) self.assertEqual(decoded.event_time.precision(), precision) + def test_java_datetime_bytes(self): + # Bytes from the Java SDK's RowCoder for a SqlTypes.DATETIME field, read + # with the schema older SDKs send, minus the Java-serialized payload. Their + # STRING "" argument means micros. + schema = schema_pb2.Schema( + id="java_datetime", + fields=[ + schema_pb2.Field( + name="f_datetime", + type=schema_pb2.FieldType( + logical_type=schema_pb2.LogicalType( + urn="beam:logical_type:datetime:v1", + representation=schema_pb2.FieldType( + row_type=schema_pb2.RowType( + schema=schema_pb2.Schema( + id="java_datetime_repr", + fields=[ + schema_pb2.Field( + name="Date", + type=schema_pb2.FieldType( + atomic_type=schema_pb2.INT64)), + schema_pb2.Field( + name="Time", + type=schema_pb2.FieldType( + atomic_type=schema_pb2.INT64)), + ]))), + argument_type=schema_pb2.FieldType( + atomic_type=schema_pb2.STRING), + argument=schema_pb2.FieldValue( + atomic_value=schema_pb2.AtomicTypeValue( + string=''))))), + ]) + coder = RowCoder(schema) + for encoded, expected in [ + # 2020-08-13T14:14:14.123456 + (b'\x01\x00\x02\x00\xb7\x90\x01\x80\xcc\xc9\xbe\xd8\xd3\x0b', + DateTime(18487, 51254123456, 6)), + # 1969-12-31T23:59:59.999999 + ( + b'\x01\x00\x02\x00\xff\xff\xff\xff\xff\xff\xff\xff\xff\x01' + b'\x98\xf8\xbb\x8a\xc9\xd2\x13', + DateTime(-1, 86399999999, 6)), + # 0001-01-01T00:00 + (b'\x01\x00\x02\x00\xc6\x8d\xd4\xff\xff\xff\xff\xff\xff\x01\x00', + DateTime(-719162, 0, 6)), + # +10000-01-01T00:00, past what datetime.datetime can hold + (b'\x01\x00\x02\x00\xa1\x81\xb3\x01\x00', DateTime(2932897, 0, 6)), + ]: + decoded = coder.decode(encoded) + self.assertEqual(decoded.f_datetime, expected) + self.assertEqual(decoded.f_datetime.precision(), expected.precision()) + self.assertEqual(coder.encode(decoded), encoded) + def test_row_coder_negative_varint(self): schema = schema_pb2.Schema( id="negative", diff --git a/sdks/python/apache_beam/portability/common_urns.py b/sdks/python/apache_beam/portability/common_urns.py index 913fb282f86b..749d5eafec7c 100644 --- a/sdks/python/apache_beam/portability/common_urns.py +++ b/sdks/python/apache_beam/portability/common_urns.py @@ -94,3 +94,4 @@ var_char = LogicalTypes.Enum.VAR_CHAR date = LogicalTypes.Enum.DATE timestamp = LogicalTypes.Enum.TIMESTAMP +datetime = LogicalTypes.Enum.DATETIME diff --git a/sdks/python/apache_beam/transforms/managed_iceberg_it_test.py b/sdks/python/apache_beam/transforms/managed_iceberg_it_test.py index b381b1960f38..9d18ba40cb51 100644 --- a/sdks/python/apache_beam/transforms/managed_iceberg_it_test.py +++ b/sdks/python/apache_beam/transforms/managed_iceberg_it_test.py @@ -26,6 +26,7 @@ from apache_beam.testing.test_pipeline import TestPipeline from apache_beam.testing.util import assert_that from apache_beam.testing.util import equal_to +from apache_beam.utils.timestamp import DateTime from apache_beam.utils.timestamp import Timestamp @@ -53,7 +54,10 @@ def _create_row(self, num: int): float_=(num + float(num) / 100), arr_=[num, num, num], date_=datetime.date.today() - datetime.timedelta(days=num), - timestamp_=Timestamp(123 * num, 456 * num)) + timestamp_=Timestamp(123 * num, 456 * num), + datetime_=DateTime.from_datetime( + datetime.datetime(2020, 8, 13, 14, 14, 14) + + datetime.timedelta(days=num, microseconds=num))) def test_write_read_pipeline(self): biglake_catalog_props = { diff --git a/sdks/python/apache_beam/typehints/schemas.py b/sdks/python/apache_beam/typehints/schemas.py index e07d8c36cb49..2abc2bddf3e4 100644 --- a/sdks/python/apache_beam/typehints/schemas.py +++ b/sdks/python/apache_beam/typehints/schemas.py @@ -34,6 +34,7 @@ bytes <-----> BYTES Buffer ------> BYTES Timestamp <-----> LogicalType(urn="beam:logical_type:micros_instant:v1") + DateTime <-----> LogicalType(urn="beam:logical_type:datetime:v1") datetime.date <-----> LogicalType(urn="beam:logical_type:date:v1") datetime.time <-----> LogicalType(urn="beam:logical_type:time:v1") Decimal <-----> LogicalType(urn="beam:logical_type:fixed_decimal:v1") @@ -104,6 +105,7 @@ from apache_beam.typehints.schema_registry import SchemaTypeRegistry from apache_beam.utils import proto_utils from apache_beam.utils.python_callable import PythonCallableWithSource +from apache_beam.utils.timestamp import DateTime from apache_beam.utils.timestamp import Timestamp # Simplify to collections.abc implementation once Python 3.11 is deprecated. @@ -1239,6 +1241,87 @@ def to_language_type(self, value): return self.EPOCH + datetime.timedelta(days=value) +DateTimeRepresentation = NamedTuple( + 'DateTimeRepresentation', [('Date', np.int64), ('Time', np.int64)]) + +_NANOS_PER_DAY = 86400 * 10**9 + + +@LogicalType._register_internal +class DateTimeLogicalType(LogicalType[DateTime, + DateTimeRepresentation, + np.int32]): + """Logical type for ``DateTime``, a date and wall-clock time with no zone. + + ``Date`` counts days since 1970-01-01. ``Time`` counts nanoseconds since + midnight, whatever the precision. + + The argument is a precision from 0 to 9 and defaults to 6, like Java's + ``SqlTypes.DATETIME``. + """ + def __init__( + self, precision: Optional[Union[int, np.integer, str]] = None) -> None: + # Older SDKs send a STRING "" argument, or none, and both mean micros. + if precision is None or precision == '': + precision = DateTime.MICROS_PRECISION + # The argument arrives as np.int32 when decoded from a schema proto. + if not isinstance(precision, (int, np.integer)): + raise ValueError( + 'DateTime precision must be an integer, but was %r.' % (precision, )) + precision = int(precision) + if not 0 <= precision <= DateTime.NANOS_PRECISION: + raise ValueError( + 'DateTime precision must be between 0 and %d (inclusive), ' + 'but was %d.' % (DateTime.NANOS_PRECISION, precision)) + self._precision = precision + + @classmethod + def urn(cls): + return common_urns.datetime.urn + + @classmethod + def language_type(cls): + return DateTime + + @classmethod + def representation_type(cls): + return DateTimeRepresentation + + @classmethod + def argument_type(cls): + return np.int32 + + def argument(self): + return self._precision + + @classmethod + def _from_typing(cls, typ): + return cls() + + def to_representation_type(self, value: DateTime) -> DateTimeRepresentation: + if not isinstance(value, DateTime): + raise TypeError( + 'Expected a DateTime, but got %r. Use DateTime.from_datetime to ' + 'convert a datetime.datetime.' % (value, )) + value = value.to_precision(self._precision) + return DateTimeRepresentation( + value.epoch_day(), + value.to_precision(DateTime.NANOS_PRECISION).time_of_day()) + + def to_language_type(self, value) -> DateTime: + nanos = int(value.Time) + if not 0 <= nanos < _NANOS_PER_DAY: + raise ValueError( + 'Invalid Time %d for DateTime: it must count nanoseconds within a ' + 'day.' % nanos) + scale = 10**(DateTime.NANOS_PRECISION - self._precision) + if nanos % scale: + raise ValueError( + 'Invalid Time %d for DateTime with precision %d.' % + (nanos, self._precision)) + return DateTime(int(value.Date), nanos // scale, self._precision) + + @LogicalType._register_internal class PythonCallable(NoArgumentLogicalType[PythonCallableWithSource, str]): """A logical type for PythonCallableSource objects.""" diff --git a/sdks/python/apache_beam/typehints/schemas_test.py b/sdks/python/apache_beam/typehints/schemas_test.py index a41df70c5a8e..998fd8d57f2a 100644 --- a/sdks/python/apache_beam/typehints/schemas_test.py +++ b/sdks/python/apache_beam/typehints/schemas_test.py @@ -52,6 +52,7 @@ from apache_beam.typehints.schemas import typing_from_runner_api from apache_beam.typehints.schemas import typing_to_runner_api from apache_beam.typehints.testing.strategies import named_fields +from apache_beam.utils.timestamp import DateTime from apache_beam.utils.timestamp import Timestamp # Simplify to collections.abc implementation once Python 3.11 is deprecated. @@ -902,6 +903,89 @@ def test_from_runner_api_rejects_missing_argument(self): schemas.LogicalType.from_runner_api(proto) +class DateTimeLogicalTypeTest(unittest.TestCase): + def test_typehints(self): + logical_type = typing_to_runner_api(DateTime).logical_type + self.assertEqual(logical_type.urn, 'beam:logical_type:datetime:v1') + # Precision 6, the same type as Java's SqlTypes.DATETIME. + self.assertEqual(logical_type.argument_type.atomic_type, schema_pb2.INT32) + self.assertEqual(logical_type.argument.atomic_value.int32, 6) + self.assertEqual( + [(f.name, f.type.atomic_type) + for f in logical_type.representation.row_type.schema.fields], + [('Date', schema_pb2.INT64), ('Time', schema_pb2.INT64)]) + # datetime.datetime fields keep their pickled encoding. + self.assertEqual( + typing_to_runner_api(datetime.datetime).logical_type.urn, + schemas.PYTHON_ANY_URN) + + def test_from_runner_api_argument_shapes(self): + def from_proto(argument_type=None, argument=None): + proto = schema_pb2.LogicalType( + urn='beam:logical_type:datetime:v1', + representation=typing_to_runner_api(schemas.DateTimeRepresentation)) + if argument_type is not None: + proto.argument_type.CopyFrom( + schema_pb2.FieldType(atomic_type=argument_type)) + proto.argument.CopyFrom(schema_pb2.FieldValue(atomic_value=argument)) + return schemas.LogicalType.from_runner_api(proto) + + # Older SDKs send a STRING "" argument, or none, and both mean micros. + self.assertEqual(from_proto().argument(), 6) + self.assertEqual( + from_proto(schema_pb2.STRING, + schema_pb2.AtomicTypeValue(string='')).argument(), + 6) + nanos = from_proto(schema_pb2.INT32, schema_pb2.AtomicTypeValue(int32=9)) + self.assertIsInstance(nanos, schemas.DateTimeLogicalType) + self.assertEqual(nanos.argument(), 9) + self.assertEqual( + nanos.to_language_type( + schemas.DateTimeRepresentation(np.int64(0), np.int64(1))), + DateTime(0, 1, 9)) + with self.assertRaises(ValueError): + from_proto(schema_pb2.INT32, schema_pb2.AtomicTypeValue(int32=10)) + with self.assertRaises(ValueError): + from_proto(schema_pb2.STRING, schema_pb2.AtomicTypeValue(string='6')) + + def test_explicit_precision(self): + for precision, time_of_day, time in [ + (3, 51_254_123, 51_254_123_000_000), + (6, 51_254_123_456, 51_254_123_456_000), + (9, 51_254_123_456_789, 51_254_123_456_789), + ]: + logical_type = schemas.DateTimeLogicalType(precision) + value = DateTime(18487, time_of_day, precision) + self.assertEqual( + logical_type.to_representation_type(value), (18487, time)) + back = logical_type.to_language_type( + schemas.DateTimeRepresentation(np.int64(18487), np.int64(time))) + self.assertEqual(back, value) + self.assertEqual(back.precision(), precision) + + micros = schemas.DateTimeLogicalType(6) + self.assertEqual( + micros.to_representation_type(DateTime(18487, 51_254_123, 3)), + (18487, 51_254_123_000_000)) + with self.assertRaises(ValueError): + micros.to_representation_type(DateTime(18487, 51_254_123_456_789, 9)) + # Java never sends a time outside the day, or digits finer than the + # precision. + for logical_type in [schemas.DateTimeLogicalType(), micros]: + for time in [-1, 86_400 * 10**9]: + with self.assertRaises(ValueError): + logical_type.to_language_type( + schemas.DateTimeRepresentation(np.int64(0), np.int64(time))) + with self.assertRaises(ValueError): + schemas.DateTimeLogicalType(3).to_language_type( + schemas.DateTimeRepresentation(np.int64(0), np.int64(1))) + + def test_rejects_non_datetime_values(self): + with self.assertRaisesRegex(TypeError, 'from_datetime'): + schemas.DateTimeLogicalType().to_representation_type( + datetime.datetime(2020, 8, 13)) + + class HypothesisTest(unittest.TestCase): # There is considerable variablility in runtime for this test, disable # deadline. diff --git a/sdks/python/apache_beam/utils/timestamp.py b/sdks/python/apache_beam/utils/timestamp.py index b222516fb228..a8c1db747095 100644 --- a/sdks/python/apache_beam/utils/timestamp.py +++ b/sdks/python/apache_beam/utils/timestamp.py @@ -24,9 +24,11 @@ # mypy: disallow-untyped-defs import datetime +import functools import re import time import zoneinfo +from typing import TYPE_CHECKING from typing import Optional from typing import Union from typing import overload @@ -38,6 +40,9 @@ from apache_beam.portability import common_urns +if TYPE_CHECKING: + import pyarrow + # types compatible with Timestamp.of() TimestampTypes = Union[int, float, 'Timestamp'] # types compatible with Duration.of() @@ -652,3 +657,211 @@ def __mod__(self, other: DurationTypes) -> 'Duration': # The minimum granularity / interval expressible in a Timestamp / Duration # object. TIME_GRANULARITY = Duration(micros=1) + +_SECONDS_PER_DAY = 86400 +_EPOCH_ORDINAL = datetime.date(1970, 1, 1).toordinal() +# Arrow timestamp units, coarsest first, with the precision each one holds. +_ARROW_UNIT_PRECISIONS = {'s': 0, 'ms': 3, 'us': 6, 'ns': 9} + + +@functools.total_ordering +class DateTime(object): + """A date and wall-clock time with no time zone, at a precision from 0 to 9. + + This is the Python type for Beam's ``datetime:v1`` logical type, which Java + holds as a ``LocalDateTime``. + + It stores the days since 1970-01-01 and the time since midnight, in units of + ``10**-precision`` seconds, as integers. It currently has no arithmetic. To + compute with a value, convert it with ``to_datetime()`` or ``to_arrow()``. + """ + MICROS_PRECISION = 6 + NANOS_PRECISION = 9 + + def __init__( + self, + epoch_day: int = 0, + time_of_day: int = 0, + precision: int = MICROS_PRECISION) -> None: + for name, value in (('epoch_day', epoch_day), + ('time_of_day', time_of_day), + ('precision', precision)): + if not isinstance(value, int): + raise TypeError( + 'Cannot interpret %s %s as %s.' % (value, type(value), name)) + if not 0 <= precision <= DateTime.NANOS_PRECISION: + raise ValueError( + 'DateTime precision must be between 0 and %d (inclusive), ' + 'but was %d.' % (DateTime.NANOS_PRECISION, precision)) + days, self._time_of_day = divmod( + time_of_day, _SECONDS_PER_DAY * _POW_10[precision]) + self._epoch_day = epoch_day + days + self._precision = precision + + def epoch_day(self) -> int: + """Returns the number of days since 1970-01-01.""" + return self._epoch_day + + def time_of_day(self) -> int: + """Returns the time since midnight, in units of 10**-precision seconds.""" + return self._time_of_day + + def precision(self) -> int: + """Returns the precision of this DateTime.""" + return self._precision + + def _total(self, precision: int) -> int: + """Returns the time since 1970-01-01T00:00 in units of 10**-precision s. + + ``precision`` must be at least this value's precision, so scaling up is + always exact. + """ + return ( + self._epoch_day * _SECONDS_PER_DAY * _POW_10[precision] + + self._time_of_day * _POW_10[precision - self._precision]) + + def to_precision( + self, precision: int, allow_lossy_conversion: bool = False) -> 'DateTime': + """Returns this DateTime converted to the given precision. + + A finer precision is always exact. A coarser one raises ValueError when it + would drop digits. With allow_lossy_conversion=True, it floors the value + instead. + """ + if precision == self._precision: + return self + if not 0 <= precision <= DateTime.NANOS_PRECISION: + raise ValueError( + 'DateTime precision must be between 0 and %d (inclusive), ' + 'but was %d.' % (DateTime.NANOS_PRECISION, precision)) + if precision > self._precision: + return DateTime( + self._epoch_day, + self._time_of_day * _POW_10[precision - self._precision], + precision) + scale = _POW_10[self._precision - precision] + if self._time_of_day % scale and not allow_lossy_conversion: + raise ValueError( + '%r cannot be represented exactly at precision %d. Set ' + 'allow_lossy_conversion=True to truncate it.' % (self, precision)) + return DateTime(self._epoch_day, self._time_of_day // scale, precision) + + @classmethod + def from_datetime(cls, dt: datetime.datetime) -> 'DateTime': + """Creates a DateTime from a naive ``datetime.datetime``. + + The result has microsecond precision. A ``pandas.Timestamp`` that carries + nanoseconds gets nanosecond precision, so none of its digits are lost. + """ + if not isinstance(dt, datetime.datetime): + raise TypeError( + 'Cannot interpret %s %s as a datetime.datetime.' % (dt, type(dt))) + if dt.tzinfo is not None: + raise ValueError( + '%s has a time zone, which makes it an instant. Use Timestamp for ' + 'instants.' % dt) + epoch_day = dt.toordinal() - _EPOCH_ORDINAL + seconds = dt.hour * 3600 + dt.minute * 60 + dt.second + micros = seconds * _POW_10[DateTime.MICROS_PRECISION] + dt.microsecond + nanosecond = getattr(dt, 'nanosecond', 0) + if nanosecond: + return cls( + epoch_day, micros * 1000 + nanosecond, DateTime.NANOS_PRECISION) + return cls(epoch_day, micros, DateTime.MICROS_PRECISION) + + def _midnight(self) -> datetime.datetime: + try: + return datetime.datetime.fromordinal(self._epoch_day + _EPOCH_ORDINAL) + except (ValueError, OverflowError) as e: + raise ValueError( + 'Day %d since 1970-01-01 is outside the years 1 to 9999 that ' + 'datetime supports.' % self._epoch_day) from e + + def to_datetime( + self, allow_lossy_conversion: bool = False) -> datetime.datetime: + """Returns this DateTime as a naive ``datetime.datetime``. + + ``datetime.datetime`` stops at microseconds. A DateTime with a finer + precision needs allow_lossy_conversion=True, which floors the value to the + microsecond. Years outside 1 to 9999 raise ValueError. + """ + if (self._precision > DateTime.MICROS_PRECISION and + not allow_lossy_conversion): + raise ValueError( + 'Converting %r to datetime truncates it to microseconds. Set ' + 'allow_lossy_conversion=True to allow this conversion.' % self) + micros = self.to_precision( + DateTime.MICROS_PRECISION, allow_lossy_conversion=True)._time_of_day + return self._midnight() + datetime.timedelta(microseconds=micros) + + @classmethod + def from_arrow(cls, scalar: 'pyarrow.TimestampScalar') -> 'DateTime': + """Creates a DateTime from a pyarrow timestamp with no time zone. + + The units ``s``, ``ms``, ``us`` and ``ns`` give precisions 0, 3, 6 and 9. + """ + import pyarrow as pa + # The messages name the scalar's type, because formatting the scalar itself + # calls as_py(), which fails past year 9999. + if not isinstance(scalar, pa.TimestampScalar): + raise TypeError( + 'Expected a pyarrow TimestampScalar, but got %s.' % type(scalar)) + if scalar.type.tz is not None: + raise ValueError( + 'A pyarrow %s has a time zone, which makes it an instant. Use ' + 'Timestamp for instants.' % scalar.type) + if not scalar.is_valid: + raise ValueError('Cannot create a DateTime from a null timestamp.') + return cls(0, scalar.value, _ARROW_UNIT_PRECISIONS[scalar.type.unit]) + + def to_arrow(self) -> 'pyarrow.TimestampScalar': + """Returns this DateTime as a pyarrow timestamp with no time zone. + + The unit is the coarsest one that holds this precision. Arrow counts units + in 64 bits, so nanosecond values only reach the years 1677 to 2262. + """ + import pyarrow as pa + unit, unit_precision = next( + (unit, unit_precision) + for unit, unit_precision in _ARROW_UNIT_PRECISIONS.items() + if self._precision <= unit_precision) + try: + return pa.scalar(self._total(unit_precision), type=pa.timestamp(unit)) + except OverflowError as e: + raise ValueError( + '%r does not fit in a pyarrow timestamp[%s].' % (self, unit)) from e + + def isoformat(self) -> str: + """Returns ``YYYY-MM-DDTHH:MM:SS``, plus the fraction when it's non-zero. + + The fraction has as many digits as the precision. Years outside 1 to 9999 + raise ValueError. + """ + seconds, fraction = divmod(self._time_of_day, _POW_10[self._precision]) + result = (self._midnight() + + datetime.timedelta(seconds=seconds)).isoformat() + if fraction: + result += '.%0*d' % (self._precision, fraction) + return result + + def __repr__(self) -> str: + try: + return 'DateTime(%s)' % self.isoformat() + except ValueError: + return 'DateTime(epoch_day=%d, time_of_day=%d, precision=%d)' % ( + self._epoch_day, self._time_of_day, self._precision) + + def __eq__(self, other: object) -> bool: + if not isinstance(other, DateTime): + return NotImplemented + precision = max(self._precision, other._precision) + return self._total(precision) == other._total(precision) + + def __lt__(self, other: object) -> bool: + if not isinstance(other, DateTime): + return NotImplemented + precision = max(self._precision, other._precision) + return self._total(precision) < other._total(precision) + + def __hash__(self) -> int: + return hash(self._total(DateTime.NANOS_PRECISION)) diff --git a/sdks/python/apache_beam/utils/timestamp_test.py b/sdks/python/apache_beam/utils/timestamp_test.py index a7eb169c8d30..485233934eb0 100644 --- a/sdks/python/apache_beam/utils/timestamp_test.py +++ b/sdks/python/apache_beam/utils/timestamp_test.py @@ -27,9 +27,20 @@ from google.protobuf import duration_pb2 from google.protobuf import timestamp_pb2 +from apache_beam.utils.timestamp import DateTime from apache_beam.utils.timestamp import Duration from apache_beam.utils.timestamp import Timestamp +try: + import pandas +except ImportError: + pandas = None + +try: + import pyarrow +except ImportError: + pyarrow = None + class TimestampTest(unittest.TestCase): def test_of(self): @@ -479,5 +490,133 @@ def test_to_proto(self): self.assertEqual(actual_dur_proto, expected_dur_proto) +class DateTimeTest(unittest.TestCase): + def test_constructor(self): + dt = DateTime(epoch_day=18487, time_of_day=51254123456789, precision=9) + self.assertEqual((dt.epoch_day(), dt.time_of_day(), dt.precision()), + (18487, 51254123456789, 9)) + self.assertEqual(DateTime().precision(), DateTime.MICROS_PRECISION) + + # A time of day past midnight carries into the next day, and a negative + # one borrows from the previous day. + carried = DateTime(0, 86_400_500, 3) + self.assertEqual((carried.epoch_day(), carried.time_of_day()), (1, 500)) + borrowed = DateTime(0, -1, 6) + self.assertEqual((borrowed.epoch_day(), borrowed.time_of_day()), + (-1, 86_399_999_999)) + + with self.assertRaises(ValueError): + DateTime(0, 0, precision=10) + with self.assertRaises(ValueError): + DateTime(0, 0, precision=-1) + with self.assertRaises(TypeError): + DateTime(0, 1.5) # type: ignore[arg-type] + + def test_equality_hash_and_order(self): + self.assertEqual(DateTime(1, 500, 3), DateTime(1, 500_000_000, 9)) + self.assertEqual( + hash(DateTime(1, 500, 3)), hash(DateTime(1, 500_000_000, 9))) + self.assertNotEqual(DateTime(1, 1, 9), DateTime(1, 0, 6)) + self.assertGreater(DateTime(1, 1, 9), DateTime(1, 0, 6)) + self.assertLess(DateTime(-1, 86_399_999_999_999, 9), DateTime(0, 0, 0)) + # Comparing with a datetime.datetime takes an explicit conversion. + self.assertNotEqual(DateTime(0), datetime.datetime(1970, 1, 1)) + + def test_precision_conversion(self): + self.assertEqual( + DateTime(0, 123, 3).to_precision(9).time_of_day(), 123_000_000) + nanos = DateTime(-1, 86_399_999_999_999, 9) + with self.assertRaises(ValueError): + nanos.to_precision(6) + floored = nanos.to_precision(6, allow_lossy_conversion=True) + self.assertEqual((floored.epoch_day(), floored.time_of_day()), + (-1, 86_399_999_999)) + with self.assertRaises(ValueError): + nanos.to_precision(10) + + def test_datetime_conversions(self): + for dt, expected in [ + (datetime.datetime(1970, 1, 1), DateTime(0, 0)), + (datetime.datetime(1969, 12, 31, 23, 59, 59, 999999), + DateTime(-1, 86_399_999_999)), + (datetime.datetime.min, DateTime(-719162, 0)), + (datetime.datetime.max, DateTime(2932896, 86_399_999_999)), + ]: + self.assertEqual(DateTime.from_datetime(dt), expected) + self.assertEqual(DateTime.from_datetime(dt).precision(), 6) + self.assertEqual(expected.to_datetime(), dt) + + with self.assertRaises(ValueError): + DateTime.from_datetime( + datetime.datetime(2020, 1, 1, tzinfo=datetime.timezone.utc)) + with self.assertRaises(TypeError): + DateTime.from_datetime(datetime.date(2020, 1, 1)) # type: ignore[arg-type] + + nanos = DateTime(18487, 51254123456789, 9) + with self.assertRaises(ValueError): + nanos.to_datetime() + self.assertEqual( + nanos.to_datetime(allow_lossy_conversion=True), + datetime.datetime(2020, 8, 13, 14, 14, 14, 123456)) + # Java can send year 10000, which datetime.datetime cannot hold. + with self.assertRaises(ValueError): + DateTime(2932897, 0).to_datetime() + + @unittest.skipIf(pandas is None, 'pandas is not installed') + def test_from_datetime_keeps_pandas_nanoseconds(self): + dt = DateTime.from_datetime( + pandas.Timestamp('2020-08-13T14:14:14.123456789')) + self.assertEqual(dt, DateTime(18487, 51254123456789, 9)) + self.assertEqual(dt.precision(), 9) + + @unittest.skipIf(pyarrow is None, 'pyarrow is not installed') + def test_arrow_conversions(self): + for dt, unit, value, back_precision in [ + (DateTime(18487, 51254, 0), 's', 1597328054, 0), + (DateTime(18487, 51254123, 3), 'ms', 1597328054123, 3), + (DateTime(18487, 512541234, 4), 'us', 1597328054123400, 6), + (DateTime(18487, 51254123456, 6), 'us', 1597328054123456, 6), + (DateTime(18487, 51254123456789, 9), 'ns', 1597328054123456789, 9), + ]: + scalar = dt.to_arrow() + self.assertEqual(scalar.type, pyarrow.timestamp(unit)) + self.assertEqual(scalar.value, value) + back = DateTime.from_arrow(scalar) + self.assertEqual(back, dt) + self.assertEqual(back.precision(), back_precision) + + self.assertEqual( + DateTime.from_arrow(pyarrow.scalar(-1, type=pyarrow.timestamp('ns'))), + DateTime(-1, 86_399_999_999_999, 9)) + # Past year 9999, so the error message mustn't format the value itself. + with self.assertRaises(ValueError): + DateTime.from_arrow( + pyarrow.scalar(3 * 10**17, type=pyarrow.timestamp('us', tz='UTC'))) + with self.assertRaises(ValueError): + DateTime.from_arrow(pyarrow.scalar(None, type=pyarrow.timestamp('us'))) + with self.assertRaises(TypeError): + DateTime.from_arrow(pyarrow.scalar(1)) + # Arrow's nanosecond timestamps stop in 2262. + with self.assertRaises(ValueError): + DateTime(2932897, 0, 9).to_arrow() + + def test_repr(self): + self.assertEqual( + repr(DateTime(18487, 51254123456, 6)), + 'DateTime(2020-08-13T14:14:14.123456)') + self.assertEqual( + repr(DateTime(18487, 51254123, 3)), 'DateTime(2020-08-13T14:14:14.123)') + self.assertEqual( + repr(DateTime(18487, 51254 * 10**9, 9)), + 'DateTime(2020-08-13T14:14:14)') + self.assertEqual( + DateTime(-1, 86_399_999_999).isoformat(), '1969-12-31T23:59:59.999999') + with self.assertRaises(ValueError): + DateTime(2932897, 0).isoformat() + self.assertEqual( + repr(DateTime(2932897, 0)), + 'DateTime(epoch_day=2932897, time_of_day=0, precision=6)') + + if __name__ == '__main__': unittest.main() From ace898992552ad79b5da29a737c9f2e8603ac7c0 Mon Sep 17 00:00:00 2001 From: Ahmed Abualsaud Date: Fri, 20 Nov 2026 16:58:18 -0800 Subject: [PATCH 2/2] Add the PR link to CHANGES.md --- CHANGES.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/CHANGES.md b/CHANGES.md index c08c42a5ee3f..0e7b17529fbe 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -111,7 +111,7 @@ * [Beam SQL] Added a live view to the SQL shell. A streaming (unbounded) SELECT shows its rows as they arrive, with an `op` column for each row's change kind ([#41313](https://github.com/apache/beam/issues/41313)). * (Python) `BatchElements` can group elements by key across workers (`key_fn`, `num_shards`), and RunInference model handlers can use it through `batch_key_fn` / `batch_key_num_shards`. `apache_beam.ml.inference.prefix_batching` adds a `PrefixBatchingConfig` and prompt/chat prefix extractors so LLM handlers can batch requests that share a prompt prefix and hit the server's prefix cache ([#40905](https://github.com/apache/beam/pull/40905)). * (Go) Added pass-through registration for fixed and variable length string and bytes logical types ([#39684](https://github.com/apache/beam/issues/39684)). -* (Java/Python) Added DateTime as a new portable logical type (`datetime:v1`). Java `DateTime` takes a precision (`DateTime.of(p)`, `MILLIS`, `MICROS`, `NANOS`), which defaults to 6. Python maps it to the new `apache_beam.utils.timestamp.DateTime`. +* (Java/Python) Added DateTime as a new portable logical type (`datetime:v1`). Java `DateTime` takes a precision (`DateTime.of(p)`, `MILLIS`, `MICROS`, `NANOS`), which defaults to 6. Python maps it to the new `apache_beam.utils.timestamp.DateTime` ([#41550](https://github.com/apache/beam/pull/41550)). ### Performance @@ -129,7 +129,7 @@ [comment]: # "generic breaking changes if not covered in following sections." * (Java) Flink runner: batch pipelines now assign source splits to readers statically by default instead of lazily. Set `--sourceStaticSplitThresholdMb=0` to restore lazy assignment ([#40607](https://github.com/apache/beam/issues/40607)). -* (Java) `SqlTypes.DATETIME` is now `DateTime` with precision 6, so a `LocalDateTime` with digits below a microsecond throws instead of being stored. Use `DateTime.NANOS` for those values. +* (Java) `SqlTypes.DATETIME` is now `DateTime` with precision 6, so a `LocalDateTime` with digits below a microsecond throws instead of being stored. Use `DateTime.NANOS` for those values ([#41550](https://github.com/apache/beam/pull/41550)). * X behavior was changed ([#X](https://github.com/apache/beam/issues/X)). ### Package upgrades