Skip to content

Convert a Unix timestamp to date(time)

Source code

Description

Depending on the time_unit provided, this function will return a different dtype:

  • time_unit = “d” returns pl$Date
  • time_unit = “s” returns pl$Datetime("us") (pl$Datetime’s default)
  • time_unit = “ms” returns pl$Datetime("ms")
  • time_unit = “us” returns pl$Datetime("us")
  • time_unit = “ns” returns pl$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   │
#> └───────────┴───────────────────────┘
# pass a literal
pl$from_epoch(pl$lit(c(1666683077, 1666683099)), time_unit = "s")$to_series()
#> 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        │
#> └───────────┴───────────────────┘