Dumb ML
Dumb ML

Reputation: 367

How can I convert a string datetime column to a datetime column in R?

This should be pretty simple, but I can't find the correct syntax. I have a dataframe called data and it's a little like this:

Id     timestamp 
A9     2020-08-10 09:05:01.000000
B9     2020-08-10 09:04:18.000000
G1     2020-04-15 11:05:08.000000
D2     2020-01-18 19:04:05.000000
F8     2020-02-12 08:04:08.000000

However, column timestamp is a string. How can I convert to a datetime column?

I've tried this:

data$timestamp_new <- as.Date(data$timestamp,format="%Y-%m-%dT%H:%M:%OS")

and this:

data$timestamp_new <- as.POSIXct(data$timestamp,format="%Y-%m-%dT%H:%M:%OS")

Both are returnign <N/A>

Upvotes: 0

Views: 1117

Answers (2)

Ronak Shah
Ronak Shah

Reputation: 388817

You can use ymd_hms from lubridate

lubridate::ymd_hms(data$timestamp)
#[1] "2020-08-10 09:05:01 UTC" "2020-08-10 09:04:18 UTC" "2020-04-15 11:05:08 UTC"
#[4] "2020-01-18 19:04:05 UTC" "2020-02-12 08:04:08 UTC"

If you are interested only in dates, you can wrap as.Date to above result.

Upvotes: 1

akrun
akrun

Reputation: 886938

We can just use %T

as.Date(data$timestamp, "%Y-%m-%d %T")
#[1] "2020-08-10" "2020-08-10" "2020-04-15" "2020-01-18" "2020-02-12"

data

data <- structure(list(Id = c("A9", "B9", "G1", "D2", "F8"), timestamp = c("2020-08-10 09:05:01.000000", 
"2020-08-10 09:04:18.000000", "2020-04-15 11:05:08.000000", "2020-01-18 19:04:05.000000", 
"2020-02-12 08:04:08.000000")), class = "data.frame", row.names = c(NA, 
-5L))

Upvotes: 2

Related Questions