polars_xdt.from_local_datetime#

polars_xdt.from_local_datetime(expr: IntoExpr, from_tz: str | Expr, to_tz: str, ambiguous: Ambiguous = 'raise') pl.Expr#

Convert from local datetime in given time zone to new timezone.

Parameters:
expr

Expression to convert.

from_tz

Current timezone of each datetime

to_tz

Timezone to convert to

ambiguous

Determine how to deal with ambiguous datetimes:

  • ‘raise’ (default): raise

  • ‘earliest’: use the earliest datetime

  • ‘latest’: use the latest datetime

Returns:
Expr

Expression of data type DateTime.

Examples

You can go from a localized datetime back to expressing the datetimes in a single timezone with from_local_datetime.

>>> from datetime import datetime
>>> import polars_xdt as xdt
>>> df = pl.DataFrame(
...     {
...         "local_dt": [
...             datetime(2020, 10, 10, 1),
...             datetime(2020, 10, 10, 2),
...             datetime(2020, 10, 9, 20),
...         ],
...         "timezone": [
...             "Europe/London",
...             "Africa/Kigali",
...             "America/New_York",
...         ],
...     }
... )
>>> df.with_columns(
...     xdt.from_local_datetime(
...         "local_dt", pl.col("timezone"), "UTC"
...     ).alias("date")
... )
shape: (3, 3)
┌─────────────────────┬──────────────────┬─────────────────────────┐
│ local_dt            ┆ timezone         ┆ date                    │
│ ---                 ┆ ---              ┆ ---                     │
│ datetime[μs]        ┆ str              ┆ datetime[μs, UTC]       │
╞═════════════════════╪══════════════════╪═════════════════════════╡
│ 2020-10-10 01:00:00 ┆ Europe/London    ┆ 2020-10-10 00:00:00 UTC │
│ 2020-10-10 02:00:00 ┆ Africa/Kigali    ┆ 2020-10-10 00:00:00 UTC │
│ 2020-10-09 20:00:00 ┆ America/New_York ┆ 2020-10-10 00:00:00 UTC │
└─────────────────────┴──────────────────┴─────────────────────────┘