How to Convert a Character to a Timestamp in R

To convert a character to a timestamp in R, you can “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 in R.


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


  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

You can use strptime() but only specify the date parts in the format string.

# Convert a character to a POSIXlt object (timestamp)

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



[1] "2023-08-31 IST"

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

If you have a character string that represents time in hours-minutes-seconds format and you want to convert it to a timestamp, you can use the strptime() function with a format string that only specifies the time parts.

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



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

Example 3: Convert Character to Timestamp and Specify Time Zone

In R, you can specify the time zone when converting a character string to a timestamp using the strptime() function. 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"



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

If you want to convert the timestamp to another time zone afterward, you can use the attr() function to modify the “tzone” attribute, or you can use the as.POSIXct() function and then use the with_tz() function from the lubridate package to change the time zone.

Example 4: Convert a Data Frame Column to Timestamp

To convert a data frame column to a timestamp, you can “use the strptime()” function.

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

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



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

That’s it!

Related posts

Date Formats in R

Date to character in R

Get Current Date and Time in R

Date to numeric in R

as.Date() function in R

Leave a Comment