DetectPosixct: Detect and convert date-time columns in a data frame

View source: R/detect_posixct.R

DetectPosixctR Documentation

Detect and convert date-time columns in a data frame

Description

Utilities for finding character or factor columns in a data frame that hold date-time (POSIXct) information, and for converting them to POSIXct in place.

Usage

DetectPosixct(df, n = 100, formats = DefaultPosixctFormats(),
              tz = "UTC", min.frac = 1, exclude = NULL)

ConvertPosixct(dframe, tz = "UTC", ...)

DefaultPosixctFormats()

Arguments

df, dframe

The data frame to examine or convert.

n

The number of leading rows to inspect. Restricting attention to the head of the frame keeps the check inexpensive on large data sets.

formats

A character vector of candidate date-time formats, in the notation used by strptime. Each column's values are tried against these formats in order. Every format supplied by DefaultPosixctFormats carries a time component, so pure Date columns are not flagged.

tz

The time zone assumed when parsing values. In ConvertPosixct it is also passed to DetectPosixct so that detection and conversion agree.

min.frac

The minimum fraction of non-missing values in a column that must parse successfully for the column to be flagged. A value of 1 (the default) requires that every non-missing value parse.

exclude

An optional character vector of column names to leave alone. Named columns are never flagged, even if their values parse as date-times.

...

Extra arguments passed from ConvertPosixct to DetectPosixct (e.g. n, formats, min.frac, or exclude).

Value

DetectPosixct returns a two-column character matrix with one row per column that should be classified as POSIXct. The "variable" column gives the name of the flagged column, and the "format" column gives the date-time format string to pass to as.POSIXct. The matrix has zero rows if no such column is found.

ConvertPosixct returns a copy of dframe in which every detected date-time column has been replaced by a POSIXct column of the same name. Columns that are not detected as date-times are returned unchanged.

DefaultPosixctFormats returns the character vector of candidate date-time formats used by DetectPosixct when no explicit formats argument is supplied.

Author(s)

Steven L. Scott steve.the.bayesian@gmail.com

See Also

as.POSIXct, strptime.

Examples

df <- data.frame(
  id = 1:3,
  event.time = c("2020-01-01 08:30:00",
                 "2020-01-02 09:15:00",
                 "2020-01-03 10:00:00"),
  label = c("a", "b", "c"),
  stringsAsFactors = FALSE)

## Identify the date-time column(s) and the format to use.
DetectPosixct(df)

## Convert them in place.
converted <- ConvertPosixct(df)
sapply(converted, class)

## Inspect (or override) the default candidate formats.
DefaultPosixctFormats()

Boom documentation built on Sept. 16, 2026, 9:09 a.m.