What is the strptime() Function in R (4 Examples)

The strptime() function in R is “used to convert characters to time objects”.

Syntax

strptime(character_object, format, tz = "")

Parameters

  1. character_object: It is an object to be converted.
  2. format: It is a character string. The default for the format methods is “%Y-%m-%d %H:%M:%S”.
  3. 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.

Return value

The return value of the strptime() function is a “POSIXlt” object. A POSIXlt object is a data structure that represents a date and time.

Example 1: Converting a character to a time Object in R

today <- "2021-03-30"
time_obj <- strptime(today, format = "%Y-%m-%d")
time_obj

Output

[1] "2021-03-30 IST"

Let’s check the class of our converted data using the class() function.

today <- "2021-03-30"
time_obj <- strptime(today, format = "%Y-%m-%d")
class(time_obj)

Output

[1] "POSIXlt" "POSIXt"

Example 2: Passing “tz” argument to the strptime()

To set up a timezone in R using the strptime() method, pass the tz argument. The strptime() method accepts three arguments, one of which is that tz means timezone.

today <- "2021-03-30"
time_obj <- strptime(today, format = "%Y-%m-%d", tz = "EST")
time_obj

Output

[1] "2021-03-30 EST"

Example 3: Getting time object with hours, mins, and secs in R

today <- "2021-03-30 19:21:11"
time_obj <- strptime(today, format = "%Y-%m-%d %H:%M:%OS", tz = "EST")
time_obj

Output

[1] "2021-03-30 19:21:11 EST"

Example 4: Passing time object with milliseconds

To add milliseconds to a time object, we have to modify the format option.

today <- "2021-03-30 19:21:11.150"
time_obj <- strptime(today, format = "%Y-%m-%d %H:%M:%OS", tz = "EST")
time_obj

Output

[1] "2021-03-30 19:21:11 EST"

The default options of R are set to show 0 millisecond digits. For that reason, we have to update the global R options.

options(digits.secs = 3)

Now rerun the above program and observe the output.

options(digits.secs = 3)

today <- "2021-03-30 19:21:11.150"
time_obj <- strptime(today, format = "%Y-%m-%d %H:%M:%OS", tz = "EST")
time_obj

Output

[1] "2021-03-30 19:21:11.15 EST"

That’s it.

Leave a Comment