You can use the strptime and strftime functions in R to convert between character and time objects.
The strptime function converts characters to time objects and uses the following basic syntax:
strptime(character_object, format="%Y-%m-%d")
The strftime function converts time objects to characters and uses the following basic syntax:
strftime(time_object)
The following examples show how to use each function in practice.
Example 1: Use strptime Function in R
Suppose we have the following character vector in R:
#create character vector
char_data <- c("2022-01-01", "2022-01-25", "2022-02-14", "2022-03-19")
#view class of vector
class(char_data)
[1] "character"
We can use the strptime function to convert the characters to time objects:
#convert characters to time objects
time_data <- strptime(char_data, format="%Y-%m-%d")
#view new vector
time_data
[1] "2022-01-01 UTC" "2022-01-25 UTC" "2022-02-14 UTC" "2022-03-19 UTC"
#view class of new vector
class(time_data)
[1] "POSIXlt" "POSIXt"
We can see that the characters have been converted to time objects.
Note that we can also use the tz argument to convert the characters to time objects with a specific time zone.
For example, we could specify “EST” to convert the characters to time objects in the Eastern Time Zone:
#convert characters to time objects in EST time zone
time_data <- strptime(char_data, format="%Y-%m-%d", tz="EST")
#view new vector
time_data
[1] "2022-01-01 EST" "2022-01-25 EST" "2022-02-14 EST" "2022-03-19 EST"
Notice that each of the time objects now end with EST, which indicates an Eastern Time Zone.
Example 2: Use strftime Function in R
Suppose we have the following vector of time objects in R:
#create vector of time objects
time_data <- as.POSIXct(c("2022-01-01", "2022-01-25", "2022-02-14"))
#view class of vector
class(time_data)
[1] "POSIXct" "POSIXt"
We can use the strftime function to convert the time objects to characters:
#convert time objects to characters
char_data <- strftime(time_data)
#view new vector
char_data
[1] "2022-01-01" "2022-01-25" "2022-02-14"
#view class of new vector
class(char_data)
[1] "character"
We can see that the time objects have been converted to characters.
Additional Resources
The following tutorials explain how to use other common functions in R:
How to Use tabulate() Function in R
How to Use split() Function in R
How to Use match() Function in R
How to Use replicate() Function in R