Home » How to Convert a Character to a Timestamp in R

How to Convert a Character to a Timestamp in R

by Tutor Aspire

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 %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 %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 %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 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 %Y-%m-%d")

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

[1] "POSIXlt" "POSIXt" 

You can find more R tutorials on this page.

You may also like