NBB
NBB

Reputation: 39

How to convert specific date format to POSXct

Hi I'm trying to convert a factor format that is ex " 1:30 PM 4-14-2014" into a POSXct object in R. So far I've tried using the lubridate packages, as date etc. Can anyone help?

head(d$date)
1:30 PM 4-14-2014
1:36 PM 4-14-2014
1:50 PM 4-14-2014
5:30 PM 4-16-2014
6:40 PM 4-17-2014
6:46 PM 4-19-2014

Upvotes: 1

Views: 42

Answers (2)

Ronak Shah
Ronak Shah

Reputation: 388817

In lubridate, we can use parse_date_time

lubridate::parse_date_time(df$V1, "IMp mdy")
#Seems to work fine with "H" as well instead of "I"
#lubridate::parse_date_time(df$V1, "HMp mdy")

#[1] "2014-04-14 13:30:00 UTC" "2014-04-14 13:36:00 UTC" "2014-04-14 13:50:00 UTC"
#[4] "2014-04-16 17:30:00 UTC" "2014-04-17 18:40:00 UTC" "2014-04-19 18:46:00 UTC"

data

df <- structure(list(V1 = structure(1:6, .Label = c("1:30 PM 4-14-2014", 
"1:36 PM 4-14-2014", "1:50 PM 4-14-2014", "5:30 PM 4-16-2014", 
"6:40 PM 4-17-2014", "6:46 PM 4-19-2014"), class = "factor")), 
class = "data.frame", row.names = c(NA, -6L))

Upvotes: 1

akrun
akrun

Reputation: 886948

We can use

as.POSIXct(d$date, format = "%I:%M %p %m-%d-%Y")

Upvotes: 2

Related Questions