You could loop over the list of reasonable formats, using the first one that works (does not return NA):
f <- function (strings, formats) { times <- strptime(strings, formats[1]) i <- 1 while ((i < length(formats)) && any(isBad <- is.na(times))) { i <- i + 1 times[isBad] <- strptime(strings[isBad], formats[i]) } times } E.g., > s <- c("2009-04-08 1:49:47 PM", + "2009-04-08 1:49 PM", + "2011-06-17 2:01:03 AM") > fmts <- c("%Y-%m-%d %I:%M:%S %p", "%Y-%m-%d %I:%M %p") > f(s, fmts) [1] "2009-04-08 13:49:47" "2009-04-08 13:49:00" "2011-06-17 02:01:03" Bill Dunlap Spotfire, TIBCO Software wdunlap tibco.com > -----Original Message----- > From: r-help-boun...@r-project.org > [mailto:r-help-boun...@r-project.org] On Behalf Of cassie jones > Sent: Friday, June 17, 2011 9:55 AM > To: r-help@r-project.org > Subject: [R] issue with strptime > > Hi everyone, > > I have bunch of date and time observations in the format > %Y-%m-%d %I %M %S > %p. I used strptime() to read this format. But the problem is > some of the > times are in the format of %I %M %p, so for those times, > strptime is giving > me NA values. > > For example, > > strptime(paste("2009-04-08","1:49:47 PM"),format="%Y-%m-%d > %I:%M:%S %p") > > [1] "2009-04-08 13:49:47" > > > But > > strptime(paste("2009-04-08","1:49 PM"),format="%Y-%m-%d %I:%M:%S %p") > > [1] NA > > Now I have approximately 10000 observations, so I can't go > through all the > observations individually in order to find which row in the > array has this > format. > > Can anyone suggest me how to handle this issue? Is there any > way to convert > %I %M %p format to %I %M %S %p? > > Thanks in advance for the help. > > Cassie > > [[alternative HTML version deleted]] > > ______________________________________________ > R-help@r-project.org mailing list > https://stat.ethz.ch/mailman/listinfo/r-help > PLEASE do read the posting guide > http://www.R-project.org/posting-guide.html > and provide commented, minimal, self-contained, reproducible code. > ______________________________________________ R-help@r-project.org mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code.