Convert a String to a Date in R


In R language, if you have a string that you need to convert to a date, try this. This is actually a datetime.

#define string variable string_a
string_a <- "3/21/2022 13:45" 
# convert it
datetime_a <- as.POSIXct(string_a, format="%m/%d/%Y %H:%M", tz="UTC")
class(datetime_a)
datetime_a

Below is the console output in RStudio.

> string_a <- "3/21/2022 13:45" #"%m/%d/%Y %H:%M"   # 3/21/2022 13:45
> datetime_a <- as.POSIXct(string_a, format="%m/%d/%Y %H:%M", tz="UTC")
> class(datetime_a)
[1] "POSIXct" "POSIXt" 
> datetime_a
[1] "2022-03-21 13:45:00 UTC"

Data Frame

Suppose we have the following data frame with a column that contains a string of datetimes.

#define data frame
df <- data.frame(day=c("2023-03-28 14:45:18", "2023-03-28 14:00:32"), sales=c(13, 18))
#convert column of strings to datetime
df$day <- as.POSIXct(df$day, format="%Y-%m-%d %H:%M:%S", tz="UTC")
#view class of 'day' column
class(df$day)
typeof(df$day)
df

Leave a Reply