Offset a date by a relative time offset
Description
This differs from pl$col(“foo”) + Duration
in that it can
take months and leap years into account. Note that only a single minus
sign is allowed in the by
string, as the first character.
Usage
<Expr>$dt$offset_by(by)
Arguments
by
|
optional string encoding duration see details. |
Details
The by
are created with the following string language:
- 1ns \# 1 nanosecond
- 1us \# 1 microsecond
- 1ms \# 1 millisecond
- 1s \# 1 second
- 1m \# 1 minute
- 1h \# 1 hour
- 1d \# 1 day
- 1w \# 1 calendar week
- 1mo \# 1 calendar month
- 1y \# 1 calendar year
- 1i \# 1 index count
By "calendar day", we mean the corresponding time on the next day (which may not be 24 hours, due to daylight savings). Similarly for "calendar week", "calendar month", "calendar quarter", and "calendar year".
These strings can be combined:
- 3d12h4m25s \# 3 days, 12 hours, 4 minutes, and 25 seconds
Value
A polars expression
Examples
library("polars")
df <- pl$select(
dates = pl$date_range(
as.Date("2000-1-1"),
as.Date("2005-1-1"),
"1y"
)
)
df$with_columns(
date_plus_1y = pl$col("dates")$dt$offset_by("1y"),
date_negative_offset = pl$col("dates")$dt$offset_by("-1y2mo")
)
#> shape: (6, 3)
#> ┌────────────┬──────────────┬──────────────────────┐
#> │ dates ┆ date_plus_1y ┆ date_negative_offset │
#> │ --- ┆ --- ┆ --- │
#> │ date ┆ date ┆ date │
#> ╞════════════╪══════════════╪══════════════════════╡
#> │ 2000-01-01 ┆ 2001-01-01 ┆ 1998-11-01 │
#> │ 2001-01-01 ┆ 2002-01-01 ┆ 1999-11-01 │
#> │ 2002-01-01 ┆ 2003-01-01 ┆ 2000-11-01 │
#> │ 2003-01-01 ┆ 2004-01-01 ┆ 2001-11-01 │
#> │ 2004-01-01 ┆ 2005-01-01 ┆ 2002-11-01 │
#> │ 2005-01-01 ┆ 2006-01-01 ┆ 2003-11-01 │
#> └────────────┴──────────────┴──────────────────────┘
# the "by" argument also accepts expressions
df <- pl$select(
dates = pl$datetime_range(
as.POSIXct("2022-01-01", tz = "GMT"),
as.POSIXct("2022-01-02", tz = "GMT"),
interval = "6h", time_unit = "ms", time_zone = "GMT"
),
offset = pl$Series(values = c("1d", "-2d", "1mo", NA, "1y"))
)
df$with_columns(new_dates = pl$col("dates")$dt$offset_by(pl$col("offset")))
#> shape: (5, 3)
#> ┌─────────────────────────┬────────┬─────────────────────────┐
#> │ dates ┆ offset ┆ new_dates │
#> │ --- ┆ --- ┆ --- │
#> │ datetime[ms, GMT] ┆ str ┆ datetime[ms, GMT] │
#> ╞═════════════════════════╪════════╪═════════════════════════╡
#> │ 2022-01-01 00:00:00 GMT ┆ 1d ┆ 2022-01-02 00:00:00 GMT │
#> │ 2022-01-01 06:00:00 GMT ┆ -2d ┆ 2021-12-30 06:00:00 GMT │
#> │ 2022-01-01 12:00:00 GMT ┆ 1mo ┆ 2022-02-01 12:00:00 GMT │
#> │ 2022-01-01 18:00:00 GMT ┆ null ┆ null │
#> │ 2022-01-02 00:00:00 GMT ┆ 1y ┆ 2023-01-02 00:00:00 GMT │
#> └─────────────────────────┴────────┴─────────────────────────┘