Convert characters to time in R
Convert characters to time in R, we will explore how to convert characters to time objects and vice versa using the strptime
and strftime
functions in R.
These functions are part of the base
package and provide a convenient way to work with dates and times.
Basic R Syntax: Convert characters to time in R
The basic syntax for the strptime
and strftime
functions is as follows:
strptime(character, format = "%Y-%m-%d") strftime(time, format = "%Y-%m-%d")
The strptime
function converts a character string to a time object, while the strftime
function converts a time object to a character string.
Example 1: Convert Character to Time Object
We can use the strptime
function to convert a character string to a time object. For example, let’s create an example character string:
time_1 <- "2020-06-01"
We can then use the strptime
function to convert this character string to a time object:
time_1a <- strptime(time_1, format = "%Y-%m-%d")
The output will be a time object with a timezone:
time_1a # [1] "2020-06-01 CEST"
Example 2: Time Object with Time Zone
We can also specify the time zone when converting a character string to a time object. For example:
time_1b <- strptime(time_1, format = "%Y-%m-%d", tz = "EST")
The output will be a time object with the specified time zone:
Replace NA with Zero in R » Data Science Tutorials
time_1b # [1] "2020-06-01 EST"
Example 3: Time Object with Hour, Minute, and Second
We can also specify the hour, minute, and second when converting a character string to a time object. For example:
time_2 <- "2020-06-01 16:15:10" time_2a <- strptime(time_2, format = "%Y-%m-%d %H:%M:%S", tz = "EST")
The output will be a time object with the specified hour, minute, and second:
time_2a # [1] "2020-06-01 16:15:10 EST"
Example 4: Time Object with Milliseconds
We can also specify milliseconds when converting a character string to a time object. For example:
time_3 <- "2020-06-01 16:11:00.255" time_3a <- strptime(time_3, format = "%Y-%m-%d %H:%M:%S", tz = "EST")
The output will be a time object with the specified milliseconds:
time_3a # [1] "2020-06-01 16:15:10.255 EST"
Example 5: Convert Time Object to Character
We can use the strftime
function to convert a time object to a character string. For example:
time_3b <- strftime(time_3a)
The output will be a character string:
time_3b # [1] "2020-06-01 16:11:00"
By using these functions, we can easily convert between characters and time objects in R.