R – Convert String to Datetime

To convert a string into date/time in R, call as.POSIXct() function and pass the string 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 string x with date/time in format format is

as.POSIXct(x)
as.POSIXct(x, tz = "", ...)
as.POSIXct(x, tz = "", format)
as.POSIXct(x, format, tryFormats = c("%Y-%m-%d %H:%M:%OS",
                          "%Y/%m/%d %H:%M:%OS",
                          "%Y-%m-%d %H:%M",
                          "%Y/%m/%d %H:%M",
                          "%Y-%m-%d",
                          "%Y/%m/%d"))

Timezone tz is optional. tryFormats are used if we do not specify any format for the input date/time string.

ADVERTISEMENT

Examples

In the following program, we take a string in x, and covert this string to POSIXct date/time object.

Example.R

x <- "2020-01-01 14:45:18"
datetime_x <- as.POSIXct(x)
print( datetime_x )

Output

[1] "2020-01-01 14:45:18 IST"

Specify Date Format

We can also specify the date format via format parameter.

Example.R

x <- "2020-01-01 14:45:18"
datetime_x <- as.POSIXct(x, format="%Y-%m-%d")
print( datetime_x )

Output

[1] "2020-01-01 IST"

Specify Time Zone

We can also specify the time zone via tz parameter.

Example.R

x <- "2020-01-01 14:45:18"
datetime_x <- as.POSIXct(x, tz="GMT", format="%Y-%m-%d")
print( datetime_x )

Output

[1] "2020-01-01 GMT"

Conclusion

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