LNA
LNA

Reputation: 1447

Converting time to readable form in R (x-posted on Stats)

10/16/2011 9:33:32 AM
10/16/2011 9:54:45 PM
10/16/2011 14:58:23 PM
10/17/2011 9:08:32 AM

The above are a few rows from my G$time column. I wanted to convert them to readable form when I graphed Y over Time, so I tried

Time<-strptime(G$Time,format="%D  %H:$M:%S %r")

and then

Time<-strptime(G$Time,format="%m/%d/%y  %H:$M:%S %r")

but I'm coming away with NA NA NA NA when I type in "Time". Can anyone help or give me a link to a good resource? I've looked at http://stat.ethz.ch/R-manual/R-patched/library/base/html/strptime.html, but I can't seem to figure out my problem.

ETA: Problem solved.. but for future self-reference, just want to note that the G$Time format I had logged in R didn't match up to the "Time" column that was in the excel sheet. So whereas in Excel I had a timestamp that looked like "10/16/2011 9:33:32 AM", typing in G$Time in R got me "10/16/2011 9:33" with the seconds and the %r cut off. I wonder if I accidentally did something that perpetuated this case. In any case, finally figured out the small details thanks to the responders below.

Upvotes: 1

Views: 210

Answers (2)

Ben Bolker
Ben Bolker

Reputation: 226087

strptime("10/16/2011 9:08",format="%m/%d/%Y %H:%M")

works for me. You need (1) %Y capitalized for four-digit year; (2) %M, not $M (is this a typo in your question?); (3) no seconds (%S) field if there isn't one in the data; (4) no AM/PM field (%r) if there isn't one in the data.

edit: with the new data above,

strptime("10/16/2011 9:08:21 PM",format="%m/%d/%Y %r")
strptime("10/16/2011 9:08:21 PM",format="%m/%d/%Y %H:%M:%S %p")

both work for me.

Note: the formats are definitely case-sensitive (e.g. %y vs %Y matters) and may be locale-sensitive as well. According to ?strptime, %D expands to %m/%d/%y, which would (I think) fail because it's looking for a 2-digit year.

Upvotes: 2

IRTFM
IRTFM

Reputation: 263301

On statsexchange I suggested it would be better posted here, and that she could choose either of

Time<-strptime(G$Time,format="&m/%d/%Y  %H:$M")  # or

Time<-strptime(G$Time,format=""&m/%d/%Y  %R")

And it turned out that she had 2 spaces between the date and time, which was why I used them above

Upvotes: 1

Related Questions