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.
Syntax
strptime(character, format = “%Y-%m-%d %H:%M:%S”)
Parameters
- character: The name of the character to be converted.
- 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")
print(timestamp)
Output
[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")
print(timestamp)
Output
[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"
)
print(timestamp_utc)
Output
[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
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
Get Current Date and Time in R

Krunal Lathiya is a seasoned Computer Science expert with over eight years in the tech industry. He boasts deep knowledge in Data Science and Machine Learning. Versed in Python, JavaScript, PHP, R, and Golang. Skilled in frameworks like Angular and React and platforms such as Node.js. His expertise spans both front-end and back-end development. His proficiency in the Python language stands as a testament to his versatility and commitment to the craft.