-4

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"
webDevleoper101
  • 69
  • 3
  • 14
  • Probable duplicate of http://stackoverflow.com/questions/25463523/convert-variable-with-mixed-date-formats-to-one-format-in-r – Rich Scriven Aug 31 '16 at 21:32

2 Answers2

2

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"
R> 

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 in fact 'known' you can also iterate over a given set and 'guess'. I have some code in RcppBDT (on GitHub but not yet on CRAN) which deals with this:

R> library(RcppBDT)    
R> 
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"    
R>   
Dirk Eddelbuettel
  • 360,940
  • 56
  • 644
  • 725
0

Dates in R can be a tricky concept at first. Look into the as.Date() function to convert strings to dates and the stpftime() function to parse datetimes into strings. Depending on which format your current values are in, one or both of these will be useful.

  • ?strptime
  • ?as.Date

Essentially, what you're going to end up doing is parsing the various components of your dates to get what you need (e.g. Day, Month, Year), but the parsing varies depending on the current format of the string. It's hard to give a definitive answer to a broad question like this, but you'll definitely want to familiarize yourself with the above functions.

Michael Toth
  • 75
  • 10