Josh
Josh

Reputation: 1992

Formatting Date Strings in R

I have two columns of differently formatted date strings that I need to make the same format,

the first is in the form:

vt_dev_date = "6/20/2016 7:45"

the second is in the form

vt_other = "2016-06-14 20:21:29.0"

If could get them both in the same form down to the minute that would be great. I have tried

strptime(vt_dev_date,format = "%Y-%m-%d %H:%M")
strptime(vt_other,"%Y-%m-%d %H:%M")

and for the second one, it works and I get "2016-06-14 20:21:00 EDT"

But for the first string, it seems that because the month and hour are not padded with zeros, none of the formating tricks will work, becuase if I try

test_string <- "06/20/2016 07:45"
strptime(test_string,format = "%m/%d/%Y %H:%M")
[1] "2016-06-20 07:45:00 EDT"

It works, but I dont think going through every row in the column and padding each date is a great option. Any help would be appreciated.

Thanks,

josh

Upvotes: 0

Views: 89

Answers (1)

Ram K
Ram K

Reputation: 1785

How about using lubridate , as follows :

library(lubridate)

x <- c("6/20/2016 7:45","2016-06-14 20:21:29.0")

> x
[1] "6/20/2016 7:45"        "2016-06-14 20:21:29.0"

> parse_date_time(x, orders = c("mdy hm", "ymd hms"))
[1] "2016-06-20 07:45:00 UTC" "2016-06-14 20:21:29 UTC"
> 

Upvotes: 2

Related Questions