Convert a Unix timestamp to date(time)
Description
Depending on the time_unit
provided, this function will
return a different dtype:
-
time_unit = “d”
returnspl$Date
-
time_unit = “s”
returnspl$Datetime("us")
(pl$Datetime
’s default) -
time_unit = “ms”
returnspl$Datetime("ms")
-
time_unit = “us”
returnspl$Datetime("us")
-
time_unit = “ns”
returnspl$Datetime("ns")
Usage
pl$from_epoch(column, time_unit = "s")
Arguments
column
|
An Expr from which integers will be parsed. If this is a float column,
then the decimal part of the float will be ignored. Character are parsed
as column names, but other literal values must be passed to
pl$lit() .
|
time_unit
|
One of “ns” , “us” , “ms” ,
“s” , “d”
|
Value
Expr as Date or Datetime depending on the time_unit
.
Examples
library("polars")
# pass an integer column
df = pl$DataFrame(timestamp = c(1666683077, 1666683099))
df$with_columns(
timestamp_to_datetime = pl$from_epoch(pl$col("timestamp"), time_unit = "s")
)
#> shape: (2, 2)
#> ┌───────────┬───────────────────────┐
#> │ timestamp ┆ timestamp_to_datetime │
#> │ --- ┆ --- │
#> │ f64 ┆ datetime[μs] │
#> ╞═══════════╪═══════════════════════╡
#> │ 1.6667e9 ┆ 2022-10-25 07:31:17 │
#> │ 1.6667e9 ┆ 2022-10-25 07:31:39 │
#> └───────────┴───────────────────────┘
#> polars Series: shape: (2,)
#> Series: '' [datetime[μs]]
#> [
#> 2022-10-25 07:31:17
#> 2022-10-25 07:31:39
#> ]
# use different time_unit
df = pl$DataFrame(timestamp = c(12345, 12346))
df$with_columns(
timestamp_to_date = pl$from_epoch(pl$col("timestamp"), time_unit = "d")
)
#> shape: (2, 2)
#> ┌───────────┬───────────────────┐
#> │ timestamp ┆ timestamp_to_date │
#> │ --- ┆ --- │
#> │ f64 ┆ date │
#> ╞═══════════╪═══════════════════╡
#> │ 12345.0 ┆ 2003-10-20 │
#> │ 12346.0 ┆ 2003-10-21 │
#> └───────────┴───────────────────┘