To format dates in R, use the as.Date() function. Functions to convert between character representations and objects of classes
"POSIXct" representing calendar dates and times.
strftime in R
The strftime() is a built-in R function that converts the time to character objects. To change the class of a time object to character, use the strftime() method.
strftime(x, format = "", tz = "", usetz = FALSE, …)
x: It is an object to be converted: a character vector for strptime, an object converted to “POSIXlt” for strftime.
format: It is a character string. The default for the format methods is “%Y-%m-%d %H:%M:%S” if any element has a time component that is not midnight, and “%Y-%m-%d” otherwise. If the options(“digits.secs”) argument is set, up to the specified number of digits will be printed for seconds.
tz: It is a character string specifying the time zone to be used for the conversion. System-specific (see as.POSIXlt), but ” “ is the current time zone, and “GMT” is UTC. Invalid values are most commonly treated as UTC on some platforms with a warning.
usetz: It is a logical argument. Should the time zone abbreviation be appended to the output? This is used in printing times, and more reliable than using “%Z”.
Let’s define a time object in R.
tt <- "2021-03-30 IST"
Use the strftime() function to transform this time object into a character object.
tt <- "2021-03-30 IST" char_obj <- strftime(tt) char_obj
As you can see that we got the character data type from the time object using strftime() method.
Let’s check the class of the output using the class() method.
tt <- "2021-03-30 IST" char_obj <- strftime(tt) class(char_obj)
That is it. We successfully converted the time object into a character object using the strftime() method.
To convert time objects to characters in R, use the strftime() function. To convert characters to time objects in R, use the strptime() function.
That is it for strftime() Function in R tutorial.