R Data Frame – Convert Column of type String to Date Time

To convert a data frame column of type string into date/time in R, call as.POSIXct() function and pass the column as argument to this function. We may optionally pass time zone, date/time format, etc., to this function. POSIXct class represents the calendar dates and times.

Syntax

The syntax to use as.POSIXct() to convert column x of data frame df with date/time in format format is

as.POSIXct(df$x)
as.POSIXct(df$x, tz = "")
as.POSIXct(df$x, tz = "", format)

Timezone tz is optional. format is optional.

ADVERTISEMENT

Examples

Convert String Column to Date Time

In the following program, we take a data frame df, and covert the column x to POSIXct date/time objects.

Example.R

df <- data.frame(
                  x = c(
                        "2022-01-01 14:45:18",
                        "2022-02-08 10:05:18",
                        "2022-04-01 18:55:18",
                        "2022-08-01 04:45:18"
                      )
                 )
df$x <- as.POSIXct( df$x, tz = "UTC" )
print( df )
print( class(df$x) )

Output

> print( df )
                    x
1 2022-01-01 14:45:18
2 2022-02-08 10:05:18
3 2022-04-01 18:55:18
4 2022-08-01 04:45:18
> print( class(df$x) )
[1] "POSIXct" "POSIXt"

Specify Date Format

We can also specify the date format via format parameter.

Example.R

df <- data.frame(
                  x = c(
                        "2022/01/01",
                        "2022/02/08",
                        "2022/04/01",
                        "2022/08/01"
                      )
                 )
df$x <- as.POSIXct( df$x, format="%Y/%m/%d" )
print( df )
print( class(df$x) )

Output

> print( df )
           x
1 2022-01-01
2 2022-02-08
3 2022-04-01
4 2022-08-01
> print( class(df$x) )
[1] "POSIXct" "POSIXt"

Conclusion

In this R Tutorial, we learned how to convert a data frame column of type string into POSIXct date/time object, using as.POSIXct() function, with the help of examples.