webDevleoper101 webDevleoper101 - 1 year ago 92
R Question

formatting dates with R

I have two date strings in R and both are in a different format. How would I go about converting one date string to be consistent with the other. Below is an example of the two formats, don't focus on the dates but the format of the string itself. Thanks!

"Wed Aug 31 14:14:13 2016"
"09/12/2016 10:20 PM EDT"

Answer Source

See help(strptime) for the fine detail on the format strings:

R> d1 <- as.Date("Wed Aug 31 14:14:13 2016", "%a %b %d %H:%M:%S %Y")
R> d1
[1] "2016-08-31"
R> d2 <- as.Date("09/12/2016 10:20 PM EDT", "%m/%d/%Y %H:%M")
R> d2
[1] "2016-09-12"

Once they are parsed as Date objects, you can format any way you like. Ditto for Datetime objects.

Edit: And as most date formats are 'known' you can also iterate over a set and 'guess'. I am some code in RcppBDT (on GitHub but not yet CRAN) which deals with this:

R> library(RcppBDT)    
R> as.Date(toPOSIXct(c("Wed Aug 31 14:14:13 2016", "09/12/2016 10:20 PM EDT"))) 
[1] "2016-08-31" "2016-09-12"    
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download