How do I convert a character to a Timestamp in R?

To convert a character to a timestamp in R, the as.POSIXct() function can be used, which takes a character string of a specific format and converts it into a timestamp object. The string should be in the format of “yyyy-mm-dd hh:mm:ss”, and the as.POSIXct() function should also be given the timezone to use with the argument tz. Alternatively, the strptime() function can be used, which also takes a character string and converts it into a timestamp object, but it allows for greater flexibility in specifying the date and time format.


You can use the strptime() function to convert a character to a timestamp in R. This function uses the following basic syntax:

strptime(character, format = “%Y-%m-%d %H:%M:%S”)

where:

  • character: The name of the character to be converted
  • format: The timestamp format to convert the character to

This tutorial provides several examples of how to use this syntax in practice.

Example 1: Convert Character to Year-Month-Day Format

The following code shows how to convert a character to a timestamp with a year-month-date format:

#create character variable
char <- "2021-10-15"

#display class of character variable
class(char)

[1] "character"

#convert character to timestamp
time <- strptime(char, "%Y-%m-%d")

#display timestamp variable
time

[1] "2021-10-15 UTC"

#display class of timestamp variable
class(time)

[1] "POSIXlt" "POSIXt"

Example 2: Convert Character to Hours-Minutes-Seconds Format

The following code shows how to convert a character to a timestamp with hours, minutes, and seconds included:

#create character variable
char <- "2021-10-15 4:30:00"

#convert character to timestamp
time <- strptime(char, "%Y-%m-%d %H:%M:%S")

#display timestamp variable
time

[1] "2021-10-15 04:30:00 UTC"

Example 3: Convert Character to Timestamp and Specify Time Zone

The following code shows how to convert a character to a timestamp and specify the time zone as Eastern Standard Time using the tz argument:

#create character variable
char <- "2021-10-15"

#convert character to timestamp with specific time zone
time <- strptime(char, "%Y-%m-%d", tz="EST")

#display timestamp variable
time

[1] "2021-10-15 EST"

Example 4: Convert a Data Frame Column to Timestamp 

The following code shows how to convert a column in a data frame from a character to a timestamp:

#create data frame
df <- data.frame(date=c("2021-10-15", "2021-10-19", "2021-10-20"),
                 sales=c(4, 13, 19))

#display data frame
class(df$date)

[1] "character"

#convert date column to timestamp
df$date <- strptime(df$date, "%Y-%m-%d")

#display class of date column
class(df$date)

[1] "POSIXlt" "POSIXt" 

You can find more R tutorials on .

x