How do you convert a string to a datetime in R?

The as.Date() and strptime() functions can be used to convert strings representing dates and times into R’s Date class. as.Date() assumes the date string is in the format of “yyyy-mm-dd”, while strptime() allows you to specify the format of the date string. Both functions can be used with the format argument to specify the format of the input string. The as.POSIXct() and as.POSIXlt() functions can also be used to convert strings into R’s POSIXct and POSIXlt classes, which represent points in time as the number of seconds since 1970-01-01 00:00:00 UTC.


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 <- as.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 <- data.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 <- as.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 for a complete documentation of the potential datetime formats you can use.

x