Skip to content

Commit

Permalink
remove warning
Browse files Browse the repository at this point in the history
  • Loading branch information
MarcoGorelli committed Jun 10, 2024
1 parent 5cb989b commit 9fb6c57
Show file tree
Hide file tree
Showing 11 changed files with 78 additions and 190 deletions.
2 changes: 0 additions & 2 deletions py-polars/polars/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,6 @@
SQLInterfaceError,
SQLSyntaxError,
StructFieldNotFoundError,
TimeZoneAwareConstructorWarning,
UnstableWarning,
)
from polars.expr import Expr
Expand Down Expand Up @@ -247,7 +246,6 @@
"ChronoFormatWarning",
"MapWithoutReturnDtypeWarning",
"PolarsWarning",
"TimeZoneAwareConstructorWarning",
"UnstableWarning",
# core classes
"DataFrame",
Expand Down
50 changes: 0 additions & 50 deletions py-polars/polars/_utils/construction/series.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
from __future__ import annotations

import contextlib
import warnings
from datetime import date, datetime, time, timedelta
from decimal import Decimal as PyDecimal
from itertools import islice
Expand All @@ -24,7 +23,6 @@
is_simple_numpy_backed_pandas_series,
)
from polars._utils.various import (
find_stacklevel,
range_to_series,
)
from polars._utils.wrap import wrap_s
Expand Down Expand Up @@ -64,7 +62,6 @@
from polars.dependencies import numpy as np
from polars.dependencies import pandas as pd
from polars.dependencies import pyarrow as pa
from polars.exceptions import TimeZoneAwareConstructorWarning

with contextlib.suppress(ImportError): # Module not available when building docs
from polars.polars import PySeries
Expand All @@ -74,30 +71,6 @@
from polars.dependencies import pandas as pd
from polars.type_aliases import PolarsDataType

TZ_NAIVE_VALUES_WITH_TZ_AWARE_DTYPE_MSG = (
"Constructing a Series with time-zone-naive "
"datetimes and a time-zone-aware dtype results in a Series where "
"the datetimes are converted to the given time zone as if starting "
"from UTC.\n\n"
"Note: this is a breaking change since pre-1.0.0 behaviour.\n\n"
"Hint: to silence this warning, you can filter out "
"warnings of class pl.TimeZoneAwareConstructorWarning.\n"
"Alternatively, you can replace "
"`pl.Series(values, dtype=pl.Datetime({}, {}))` with one of:\n"
"- `pl.Series(values, dtype=pl.Datetime(time_unit)).dt.replace_time_zone(time_zone)`\n"
"- `pl.Series(values, dtype=pl.Datetime(time_unit)).dt.convert_time_zone(time_zone)`\n"
"depending on whether you want to replace or convert the time zone."
)
TZ_AWARE_VALUES_WITH_TZ_NAIVE_DTYPE_MSG = (
"Constructing a Series with time-zone-aware "
"datetimes and a time-zone-naive dtype results in a Series where "
"the datetimes are converted to UTC.\n\n"
"Hint: to silence this warning, you can filter out "
"warnings of class pl.TimeZoneAwareConstructorWarning.\n"
"Alternatively, you can set the time zone in the `dtype`, e.g.:\n"
" pl.Series(values, dtype=pl.Datetime({}, 'UTC'))`"
)


def sequence_to_pyseries(
name: str,
Expand Down Expand Up @@ -229,34 +202,11 @@ def sequence_to_pyseries(
if (values_dtype == Date) & (dtype == Datetime):
result = s.cast(Datetime(time_unit or "us"))
if time_zone is not None:
if time_zone != "UTC":
warnings.warn(
TZ_NAIVE_VALUES_WITH_TZ_AWARE_DTYPE_MSG.format(
time_unit or "us", time_zone
),
TimeZoneAwareConstructorWarning,
stacklevel=find_stacklevel(),
)
result = result.dt.convert_time_zone(time_zone)
return result._s

if (dtype == Datetime) and (value.tzinfo is not None or time_zone is not None):
values_tz = str(value.tzinfo) if value.tzinfo is not None else None
dtype_tz = time_zone
if values_tz is not None and dtype_tz is None and values_tz != "UTC":
warnings.warn(
TZ_AWARE_VALUES_WITH_TZ_NAIVE_DTYPE_MSG.format(time_unit or "us"),
TimeZoneAwareConstructorWarning,
stacklevel=find_stacklevel(),
)
if values_tz is None and dtype_tz is not None and dtype_tz != "UTC":
warnings.warn(
TZ_NAIVE_VALUES_WITH_TZ_AWARE_DTYPE_MSG.format(
time_unit or "us", time_zone
),
TimeZoneAwareConstructorWarning,
stacklevel=find_stacklevel(),
)
return s.dt.convert_time_zone(dtype_tz or "UTC")._s
return s._s

Expand Down
4 changes: 0 additions & 4 deletions py-polars/polars/exceptions.py
Original file line number Diff line number Diff line change
Expand Up @@ -145,10 +145,6 @@ class PolarsInefficientMapWarning(PolarsWarning): # type: ignore[misc]
"""Warning issued when a potentially slow `map_*` operation is performed."""


class TimeZoneAwareConstructorWarning(PolarsWarning): # type: ignore[misc]
"""Warning issued when constructing Series from non-UTC time-zone-aware inputs."""


class UnstableWarning(PolarsWarning): # type: ignore[misc]
"""Warning issued when unstable functionality is used."""

Expand Down
10 changes: 1 addition & 9 deletions py-polars/polars/testing/parametric/strategies/core.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
from __future__ import annotations

import warnings
from dataclasses import dataclass
from typing import TYPE_CHECKING, Any, Collection, Mapping, Sequence, overload

Expand All @@ -10,7 +9,6 @@
from polars._utils.deprecation import issue_deprecation_warning
from polars.dataframe import DataFrame
from polars.datatypes import DataType, DataTypeClass, Null
from polars.exceptions import TimeZoneAwareConstructorWarning
from polars.series import Series
from polars.string_cache import StringCache
from polars.testing.parametric.strategies._utils import flexhash
Expand Down Expand Up @@ -205,13 +203,7 @@ def series( # noqa: D417
)
)

with warnings.catch_warnings():
warnings.filterwarnings(
"ignore",
"Constructing a Series with time-zone-naive",
category=TimeZoneAwareConstructorWarning,
)
s = Series(name=name, values=values, dtype=dtype)
s = Series(name=name, values=values, dtype=dtype)

# Apply chunking
if allow_chunks and size > 1 and draw(st.booleans()):
Expand Down
19 changes: 8 additions & 11 deletions py-polars/tests/unit/constructors/test_constructors.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,6 @@
from polars._utils.construction.utils import try_get_type_hints
from polars.datatypes import PolarsDataType, numpy_char_code_to_dtype
from polars.dependencies import dataclasses, pydantic
from polars.exceptions import TimeZoneAwareConstructorWarning
from polars.testing import assert_frame_equal, assert_series_equal

if TYPE_CHECKING:
Expand Down Expand Up @@ -897,17 +896,15 @@ def test_init_1d_sequence() -> None:
[datetime(2020, 1, 1, tzinfo=timezone.utc)], schema={"ts": pl.Datetime("ms")}
)
assert df.schema == {"ts": pl.Datetime("ms", "UTC")}
with pytest.warns(TimeZoneAwareConstructorWarning, match="converted to UTC"):
df = pl.DataFrame(
[datetime(2020, 1, 1, tzinfo=timezone(timedelta(hours=1)))],
schema={"ts": pl.Datetime("ms")},
)
df = pl.DataFrame(
[datetime(2020, 1, 1, tzinfo=timezone(timedelta(hours=1)))],
schema={"ts": pl.Datetime("ms")},
)
assert df.schema == {"ts": pl.Datetime("ms", "UTC")}
with pytest.warns(TimeZoneAwareConstructorWarning, match="converted to UTC"):
df = pl.DataFrame(
[datetime(2020, 1, 1, tzinfo=ZoneInfo("Asia/Kathmandu"))],
schema={"ts": pl.Datetime("ms")},
)
df = pl.DataFrame(
[datetime(2020, 1, 1, tzinfo=ZoneInfo("Asia/Kathmandu"))],
schema={"ts": pl.Datetime("ms")},
)
assert df.schema == {"ts": pl.Datetime("ms", "UTC")}


Expand Down
19 changes: 6 additions & 13 deletions py-polars/tests/unit/constructors/test_series.py
Original file line number Diff line number Diff line change
Expand Up @@ -105,36 +105,29 @@ def test_series_init_ambiguous_datetime() -> None:
value = datetime(2001, 10, 28, 2)
dtype = pl.Datetime(time_zone="Europe/Belgrade")

with pytest.warns(pl.TimeZoneAwareConstructorWarning, match="converted to"):
result = pl.Series([value], dtype=dtype, strict=True)
result = pl.Series([value], dtype=dtype, strict=True)
expected = pl.Series([datetime(2001, 10, 28, 3)]).dt.replace_time_zone(
"Europe/Belgrade"
)
assert_series_equal(result, expected)

with pytest.warns(pl.TimeZoneAwareConstructorWarning, match="converted to"):
result = pl.Series([value], dtype=dtype, strict=False)
result = pl.Series([value], dtype=dtype, strict=False)
assert_series_equal(result, expected)


def test_series_init_nonexistent_datetime() -> None:
value = datetime(2024, 3, 31, 2, 30)
dtype = pl.Datetime(time_zone="Europe/Amsterdam")

with pytest.warns(
pl.TimeZoneAwareConstructorWarning, match="converted to the given time zone"
):
pl.Series([value], dtype=dtype, strict=True)

with pytest.warns(
pl.TimeZoneAwareConstructorWarning, match="converted to the given time zone"
):
result = pl.Series([value], dtype=dtype, strict=False)
result = pl.Series([value], dtype=dtype, strict=True)
expected = pl.Series([datetime(2024, 3, 31, 4, 30)]).dt.replace_time_zone(
"Europe/Amsterdam"
)
assert_series_equal(result, expected)

result = pl.Series([value], dtype=dtype, strict=False)
assert_series_equal(result, expected)


# https://github.com/pola-rs/polars/issues/15518
def test_series_init_np_temporal_with_nat_15518() -> None:
Expand Down
24 changes: 6 additions & 18 deletions py-polars/tests/unit/dataframe/test_df.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
from __future__ import annotations

import contextlib
import sys
import typing
from collections import OrderedDict
Expand All @@ -18,7 +17,7 @@
import polars.selectors as cs
from polars._utils.construction import iterable_to_pydf
from polars.datatypes import DTYPE_TEMPORAL_UNITS, INTEGER_DTYPES
from polars.exceptions import ComputeError, TimeZoneAwareConstructorWarning
from polars.exceptions import ComputeError
from polars.testing import (
assert_frame_equal,
assert_frame_not_equal,
Expand Down Expand Up @@ -2449,25 +2448,22 @@ def test_init_datetimes_with_timezone() -> None:
"dtype_time_zone",
"expected_time_zone",
"expected_item",
"warn",
),
[
(None, "", None, None, datetime(2020, 1, 1), False),
(None, "", None, None, datetime(2020, 1, 1)),
(
timezone(timedelta(hours=-8)),
"-08:00",
"UTC",
"UTC",
datetime(2020, 1, 1, 8, tzinfo=timezone.utc),
False,
),
(
timezone(timedelta(hours=-8)),
"-08:00",
None,
"UTC",
datetime(2020, 1, 1, 8, tzinfo=timezone.utc),
True,
),
],
)
Expand All @@ -2477,19 +2473,11 @@ def test_init_vs_strptime_consistency(
dtype_time_zone: str | None,
expected_time_zone: str,
expected_item: datetime,
warn: bool,
) -> None:
msg = r"converted to UTC"
context_manager: contextlib.AbstractContextManager[pytest.WarningsRecorder | None]
if warn:
context_manager = pytest.warns(TimeZoneAwareConstructorWarning, match=msg)
else:
context_manager = contextlib.nullcontext()
with context_manager:
result_init = pl.Series(
[datetime(2020, 1, 1, tzinfo=tzinfo)],
dtype=pl.Datetime("us", dtype_time_zone),
)
result_init = pl.Series(
[datetime(2020, 1, 1, tzinfo=tzinfo)],
dtype=pl.Datetime("us", dtype_time_zone),
)
result_strptime = pl.Series([f"2020-01-01 00:00{offset}"]).str.strptime(
pl.Datetime("us", dtype_time_zone)
)
Expand Down
Loading

0 comments on commit 9fb6c57

Please sign in to comment.