Reputation: 4398
I have dataset, df, that has a column labeled date. I would like to change the format for all of the data within this date column.
date
29/11/2019 11:28:04 AM
29/11/2019 11:28:05 AM
I would like for the column to look like this:
date
11/29/2019 11:28:04 AM
11/29/2019 11:28:05 AM
Here is the dput:
structure(list(Date = structure(1:2, .Label = c("29/11/2019 11:28:04 AM",
"29/11/2019 11:28:05 AM"), class = "factor")), class = "data.frame", row.names = c(NA,
-2L))
This is what I have tried:
newdate<- format(df$date("%m/%d/%Y" %H%m%s %d))
I realize I have the syntax wrong, I am researching this.
Upvotes: 1
Views: 69
Reputation: 887098
We can just use dmy_hms
to convert to Datetime
and then wrap with format
library(lubridate)
format(dmy_hms(df$Date), "%m/%d/%Y %I:%M:%S %p")
#[1] "11/29/2019 11:28:04 AM" "11/29/2019 11:28:05 AM"
In base R
, we can use strptime
with strftime
strftime(strptime(df$Date, format = "%d/%m/%Y %T"), "%m/%d/%Y %T")
#[1] "11/29/2019 11:28:04 AM" "11/29/2019 11:28:05 AM"
Upvotes: 1
Reputation: 388982
In base R, we can use as.POSIXct
to convert to date-time and then use format
to get data in required format.
format(as.POSIXct(df$Date, format = "%d/%m/%Y %I:%M:%S %p"), "%m/%d/%Y %I:%M:%S %p")
#[1] "11/29/2019 11:28:04 AM" "11/29/2019 11:28:05 AM"
Upvotes: 2