Reputation: 10626
I have this data frame:
dput(df)
structure(list(Time = structure(1:20, .Label = c("1/29/15 9:20 PM",
"1/29/15 9:30 AM", "1/29/15 9:30 PM", "1/29/15 9:40 AM", "1/29/15 9:40 PM",
"1/29/15 9:50 AM", "1/29/15 9:50 PM", "1/30/15 1:00 AM", "1/30/15 1:10 AM",
"1/30/15 1:20 AM", "1/30/15 1:30 AM", "1/30/15 1:40 AM", "1/30/15 1:50 AM",
"1/30/15 12:00 AM", "1/30/15 12:10 AM", "1/30/15 12:20 AM", "1/30/15 12:30 AM",
"1/30/15 12:40 AM", "1/30/15 12:50 AM", "1/30/15 2:00 AM"), class = "factor"),
Server1 = c(0, 0.5, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, NA)), .Names = c("Time", "Server1"), class = "data.frame", row.names = c(NA,
-20L))
I need to convert df$Time
as POSIXct
. I am doing this:
df$Time<-as.POSIXct(df$Time, format="%m/%d/%y %H:%M %p", tz="America/New_York")
this value: 1/30/15 12:50 AM
becomes
2015-01-30 12:50:00
, not AM but PM. Any ideas how could I convert this 12:50 AM and similar dates to AM not PM?
Upvotes: 0
Views: 82
Reputation: 176648
In the Details section of ?strptime
, in the section for "%p"
, it says, "Used in conjunction with "%I"
and not with "%H"
. So it works if you do that.
d <- structure(list(Time = structure(1:20, .Label = c("1/29/15 9:20 PM",
"1/29/15 9:30 AM", "1/29/15 9:30 PM", "1/29/15 9:40 AM", "1/29/15 9:40 PM",
"1/29/15 9:50 AM", "1/29/15 9:50 PM", "1/30/15 1:00 AM", "1/30/15 1:10 AM",
"1/30/15 1:20 AM", "1/30/15 1:30 AM", "1/30/15 1:40 AM", "1/30/15 1:50 AM",
"1/30/15 12:00 AM", "1/30/15 12:10 AM", "1/30/15 12:20 AM", "1/30/15 12:30 AM",
"1/30/15 12:40 AM", "1/30/15 12:50 AM", "1/30/15 2:00 AM"), class = "factor"),
Server1 = c(0, 0.5, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, NA)), .Names = c("Time", "Server1"), class = "data.frame",
row.names = c(NA, -20L))
d$Time <- as.POSIXct(d$Time, format="%m/%d/%y %I:%M %p", tz="America/New_York")
Upvotes: 3
Reputation: 513
Use the lubridate
package.
library(lubridate)
time$Time <- mdy_hm(time$Time)
To check:
> str(time)
'data.frame': 20 obs. of 2 variables:
$ Time : POSIXct, format: "2015-01-29 21:20:00" "2015-01-29 09:30:00" "2015-01-29 21:30:00" "2015-01-29 09:40:00" ...
$ Server1: num 0 0.5 0 1 0 0 0 0 0 0 ...
Upvotes: -1