你如何在R中将时间转换为POSIX时间

时间:2015-01-30 18:13:15

标签: r

我有这个数据框:

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))

我需要将df$Time转换为POSIXct。我这样做:

df$Time<-as.POSIXct(df$Time, format="%m/%d/%y %H:%M %p", tz="America/New_York")

此值:1/30/15 12:50 AM变为

2015-01-30 12:50:00,不是AM而是PM。任何想法如何将这个12:50 AM和类似日期转换为AM而不是PM?

2 个答案:

答案 0 :(得分:3)

?strptime详细信息部分的"%p"部分,它说,&#34;与"%I"不与"%H"。所以如果你这样做就行了。

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

答案 1 :(得分:-1)

使用lubridate包。

library(lubridate)
time$Time <- mdy_hm(time$Time)

检查:

> 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 ...