62
You can use the following syntax to convert a string to a datetime in R:
as.POSIXct(string_name, format="%Y-%m-%d %H:%M:%S", tz="UTC")
The following examples show how to use this syntax in practice:
Example 1: Convert One String to Datetime
The following code shows how to convert a single string in R to a datetime format:
#define string variable string_x 2020-01-01 14:45:18" #convert string variable to datetime variable datetime_x POSIXct(string_x, format="%Y-%m-%d %H:%M:%S", tz="UTC") #view new datetime variable datetime_x [1] "2020-01-01 14:45:18 UTC" #view class of datetime variable class(datetime_x) [1] "POSIXct" "POSIXt"
Example 2: Convert Column of Strings to Datetime
Suppose we have the following data frame with a column that contains a string of datetimes:
#define data frame df frame(day=c("2020-01-01 14:45:18", "2020-02-01 14:00:11", "2020-03-01 12:40:10", "2020-04-01 11:00:00"), sales=c(13, 18, 22, 19)) #view data frame df day sales 1 2020-01-01 14:45:18 13 2 2020-02-01 14:00:11 18 3 2020-03-01 12:40:10 22 4 2020-04-01 11:00:00 19
We can convert this column from strings to datetimes using the following syntax:
#convert column of strings to datetime df$day POSIXct(df$day, format="%Y-%m-%d %H:%M:%S", tz="UTC") #view class of 'day' column class(df$day) [1] "POSIXct" "POSIXt"
Note that in these examples we used a specific datetime format. Refer to this page for a complete documentation of the potential datetime formats you can use.
Additional Resources
How to Convert Character to Factor in R
How to Convert Factor to Numeric in R
How to Convert List to Vector in R
How to Convert Data Frame Column to Vector in R