How to Convert a Character to a Timestamp in R

To convert a character to a timestamp, use the strptime() function. This function allows you to specify the format of the date-time string so that it can be converted into a POSIXlt object, another type of date-time object.

Syntax

strptime(character, format = “%Y-%m-%d %H:%M:%S”)

Parameters

  1. character: The name of the character to be converted.
  2. format: The timestamp format to convert the character to.

Example 1: Using strptime() function

Visual representation of strptime() function

# Convert a character to a POSIXlt object (timestamp)

timestamp <- strptime("2023-08-31 12:34:56", format="%Y-%m-%d")

print(timestamp)

Output

[1] "2023-08-31 IST"

Example 2: Converting Character to Hours-Minutes-Seconds Format

Visual representation of Converting Character to Hours-Minutes-Seconds Format

timestamp <- strptime("12:34:56", format = "%H:%M:%S")

print(timestamp)

Output

[1] "2023-08-31 12:34:56 IST"

Example 3: Convert Character to Timestamp and Specify Time Zone

Visual representation of Converting Character to Timestamp and Specify Time Zone

You can set the “tz” argument to specify the time zone for the resultant POSIXlt object.

timestamp_utc <- strptime("2023-08-31 12:34:56",
  format = "%Y-%m-%d %H:%M:%S", tz = "America/New_York"
)

print(timestamp_utc)

Output

[1] "2023-08-31 12:34:56 EDT"

Example 4: Convert a Data Frame Column to Timestamp

df <- data.frame(
  id = 1:3,
  time_str = c(
    "2023-08-31 12:34:56",
    "2023-09-01 13:45:00",
    "2023-09-02 14:55:00"
  )
)
# Display data frame
class(df$time_str)

df$time_str <- strptime(df$time_str, "%Y-%m-%d")

class(df$time_str)

Output

[1] "character"
[1] "POSIXlt" "POSIXt"

That’s it!

Related posts

Date Formats

Date to character

Get Current Date and Time

Date to numeric

as.Date() function

Leave a Comment