Skip to content

Commit

Permalink
fix(rust, python): raise if tz_localize called on UTC-aware (pola-rs#…
Browse files Browse the repository at this point in the history
…6526)

Co-authored-by: MarcoGorelli <>
  • Loading branch information
MarcoGorelli authored and cojmeister committed Jan 30, 2023
1 parent 34fc1aa commit 5dd3f9b
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 6 deletions.
12 changes: 6 additions & 6 deletions polars/polars-lazy/polars-plan/src/dsl/function_expr/datetime.rs
Original file line number Diff line number Diff line change
Expand Up @@ -145,14 +145,14 @@ pub(super) fn cast_timezone(s: &Series, tz: &str) -> PolarsResult<Series> {
#[cfg(feature = "timezones")]
pub(super) fn tz_localize(s: &Series, tz: &str) -> PolarsResult<Series> {
let ca = s.datetime()?.clone();
match ca.time_zone() {
Some(tz) if tz == "UTC" => {
Ok(ca.with_time_zone(Some("UTC".into()))?.into_series())
}
Some(tz) if !tz.is_empty() => {
match (ca.time_zone(), tz) {
(Some(old_tz), _) if !old_tz.is_empty() => {
Err(PolarsError::ComputeError("Cannot localize a tz-aware datetime. Consider using 'dt.with_time_zone' or 'dt.cast_time_zone'".into()))
},
_ => {
(_, "UTC") => {
Ok(ca.with_time_zone(Some("UTC".into()))?.into_series())
}
(_, _) => {
Ok(ca.with_time_zone(Some("UTC".to_string()))?.cast_time_zone(tz)?.into_series())
}
}
Expand Down
15 changes: 15 additions & 0 deletions py-polars/tests/unit/test_datelike.py
Original file line number Diff line number Diff line change
Expand Up @@ -2178,6 +2178,21 @@ def test_tz_localize() -> None:
}


@pytest.mark.parametrize("time_zone", ["UTC", "Africa/Abidjan"])
def test_tz_localize_from_utc(time_zone: str) -> None:
ts_utc = (
pl.Series(["2018-10-28"]).str.strptime(pl.Datetime).dt.tz_localize(time_zone)
)
with pytest.raises(
ComputeError,
match=(
"^Cannot localize a tz-aware datetime. Consider using "
"'dt.with_time_zone' or 'dt.cast_time_zone'$"
),
):
ts_utc.dt.tz_localize("America/Maceio")


def test_tz_aware_truncate() -> None:
test = pl.DataFrame(
{
Expand Down

0 comments on commit 5dd3f9b

Please sign in to comment.