Time zones

You really should never, ever deal with time zones if you can help it

-- Tom Scott

The main methods for setting and converting between time zones are:

  • dt.convert_time_zone: convert from one time zone to another;
  • dt.replace_time_zone: set/unset/change time zone;

Let's look at some examples of common operations:

ts = ["2021-03-27 03:00", "2021-03-28 03:00"]
tz_naive = pl.Series("tz_naive", ts).str.strptime(pl.Datetime)
tz_aware = tz_naive.dt.replace_time_zone("UTC").rename("tz_aware")
time_zones_df = pl.DataFrame([tz_naive, tz_aware])
shape: (2, 2)
┌─────────────────────┬─────────────────────────┐
│ tz_naive            ┆ tz_aware                │
│ ---                 ┆ ---                     │
│ datetime[μs]        ┆ datetime[μs, UTC]       │
╞═════════════════════╪═════════════════════════╡
│ 2021-03-27 03:00:00 ┆ 2021-03-27 03:00:00 UTC │
│ 2021-03-28 03:00:00 ┆ 2021-03-28 03:00:00 UTC │
└─────────────────────┴─────────────────────────┘
time_zones_operations = time_zones_df.select(
    [
        pl.col("tz_aware").dt.replace_time_zone("Europe/Brussels").alias("replace time zone"),
        pl.col("tz_aware").dt.convert_time_zone("Asia/Kathmandu").alias("convert time zone"),
        pl.col("tz_aware").dt.replace_time_zone(None).alias("unset time zone"),
    ]
)
shape: (2, 3)
┌───────────────────────────────┬──────────────────────────────┬─────────────────────┐
│ replace time zone             ┆ convert time zone            ┆ unset time zone     │
│ ---                           ┆ ---                          ┆ ---                 │
│ datetime[μs, Europe/Brussels] ┆ datetime[μs, Asia/Kathmandu] ┆ datetime[μs]        │
╞═══════════════════════════════╪══════════════════════════════╪═════════════════════╡
│ 2021-03-27 03:00:00 CET       ┆ 2021-03-27 08:45:00 +0545    ┆ 2021-03-27 03:00:00 │
│ 2021-03-28 03:00:00 CEST      ┆ 2021-03-28 08:45:00 +0545    ┆ 2021-03-28 03:00:00 │
└───────────────────────────────┴──────────────────────────────┴─────────────────────┘

See the list of tz database time zones for a list of what's available.