polars.duration#

polars.duration(
*,
days: Expr | str | int | None = None,
seconds: Expr | str | int | None = None,
nanoseconds: Expr | str | int | None = None,
microseconds: Expr | str | int | None = None,
milliseconds: Expr | str | int | None = None,
minutes: Expr | str | int | None = None,
hours: Expr | str | int | None = None,
weeks: Expr | str | int | None = None,
) Expr[source]#

Create polars Duration from distinct time components.

Returns:
Expr

Expression of data type Duration.

Examples

>>> from datetime import datetime
>>> df = pl.DataFrame(
...     {
...         "dt": [datetime(2022, 1, 1), datetime(2022, 1, 2)],
...         "add": [1, 2],
...     }
... )
>>> print(df)
shape: (2, 2)
┌─────────────────────┬─────┐
│ dt                  ┆ add │
│ ---                 ┆ --- │
│ datetime[μs]        ┆ i64 │
╞═════════════════════╪═════╡
│ 2022-01-01 00:00:00 ┆ 1   │
│ 2022-01-02 00:00:00 ┆ 2   │
└─────────────────────┴─────┘
>>> with pl.Config(tbl_width_chars=120):
...     df.select(
...         (pl.col("dt") + pl.duration(weeks="add")).alias("add_weeks"),
...         (pl.col("dt") + pl.duration(days="add")).alias("add_days"),
...         (pl.col("dt") + pl.duration(seconds="add")).alias("add_seconds"),
...         (pl.col("dt") + pl.duration(milliseconds="add")).alias("add_millis"),
...         (pl.col("dt") + pl.duration(hours="add")).alias("add_hours"),
...     )
...
shape: (2, 5)
┌─────────────────────┬─────────────────────┬─────────────────────┬─────────────────────────┬─────────────────────┐
│ add_weeks           ┆ add_days            ┆ add_seconds         ┆ add_millis              ┆ add_hours           │
│ ---                 ┆ ---                 ┆ ---                 ┆ ---                     ┆ ---                 │
│ datetime[μs]        ┆ datetime[μs]        ┆ datetime[μs]        ┆ datetime[μs]            ┆ datetime[μs]        │
╞═════════════════════╪═════════════════════╪═════════════════════╪═════════════════════════╪═════════════════════╡
│ 2022-01-08 00:00:00 ┆ 2022-01-02 00:00:00 ┆ 2022-01-01 00:00:01 ┆ 2022-01-01 00:00:00.001 ┆ 2022-01-01 01:00:00 │
│ 2022-01-16 00:00:00 ┆ 2022-01-04 00:00:00 ┆ 2022-01-02 00:00:02 ┆ 2022-01-02 00:00:00.002 ┆ 2022-01-02 02:00:00 │
└─────────────────────┴─────────────────────┴─────────────────────┴─────────────────────────┴─────────────────────┘