What is the as.POSIXct() function in R?

Overview

The as.POSIXct() function in R is used to convert the character type setting default for UTC and 1970 to a POSIXct object.

Syntax

as.POSIXct(x)

Parameter value

The as.POSIXct() function takes the parameter value, x, which represents the character type for UTC.

Return value

The as.POSIXct() function returns a POSIXct object class.

Code example 1

In the example given below, we will create an exemplifying date and time object in R. The class of this object will be checked for using the class() function:

# creating a date and time object
mydate <- "2022-01-30 07:32:59"
# printing the date and time object
mydate
# checking the class object
class(mydate)

Code explanation

  • Line 2: We create a variable called mydate, which contains exemplifying data and time characters (30th of January 2022 and 07 hours, 32 minutes, and 59 seconds).
  • Line 5: We print the variable called mydate.
  • Line 8: We obtain the class object of the variable x, using the class() function.

Note: It is worth noting that from the output of the code given above, "character" was returned by the class() function. Therefore, to convert this character to the POSIXlt class, we will simply make use of the as.POSIXct() function.

Code example 2

# creating a date and time object
mydate <- "2022-01-30 07:32:59"
# implementing the as.POSIXct() function
mydate_POSIX = as.POSIXct(mydate)
# printing the POSIXit object
mydate_POSIX
# checking the class object
class(mydate_POSIX)

Code explanation

  • Line 5: We implement the as.POSIXct() function on the variable called mydate. We assign the result to a variable called mydate_POSIX.
  • Line 8: We print the variable called mydate_POSIX.
  • Line 11: We also check for the class of the object of the variable mydate_POSIX, using the class() function.

Note: When the class function returns a POSIXct object, then this means that we successfully converted the character type of UTC to a POSIXct object.

Free Resources