2

我有这个向量表示时间记录为小时(0 到 24)和分钟(0 到 59)。我想将其转换为 R 中的 %H:%M 时间格式,以便我可以使用 difftime 之类的函数。

str(SF5$ES_TIME)
 int [1:11452] 1940 600 5 1455 1443 2248 1115 900 200 420 ...

这是我尝试过的,但在这两种情况下,我都有一个错误:

>SF5$time1<-as.POSIXct(SF5$ES_TIME, format = "%H:%M",tz="EST")
Error in as.POSIXct.numeric(SF5$ES_TIME, format = "%H:%M", tz = "EST") : 
  'origin' must be supplied
SF5$time1<-as.POSIXct(as.character(SF5$ES_TIME), format="%H:%M",tz="")
> str(SF5$time1)
POSIXct[1:11452], format: NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA ...

任何帮助或阅读建议将不胜感激!谢谢你,奥雷莉

4

2 回答 2

3

好吧,错误消息告诉您提供origin,一分钟是 60 秒,所以:

SF5 <- list(ES_TIME=as.integer(c(1940,600,5,1455,1443,2248,1115,900,200,420)))

x <- as.POSIXct(SF5$ES_TIME*60, origin="1970-01-01")
format(x, format="%H:%M")
#[1] "08:20" "10:00" "00:05" "00:15" "00:03" "13:28" "18:35" "15:00" "03:20" "07:00"

请注意,POSIXct日期只是一个数字(带有类),因此您需要format调用来打印它 - 默认打印x将打印完整的日期信息(年/月/日等)。

...任何起源日期都可以,因为您不关心它,但它1970-01-01是通常的起源...

于 2012-04-04T18:29:22.340 回答
0

I was able to crack down the code! Thank you all for your tip!

#1) as suggested by Justin : put all numbers into four digits with zero padding
    SF5$ES_TIME2<-sprintf("%04d",SF5$ES_TIME) 
#2) Matched these %H%M with their corresponding date %y-%m-%d
    SF5$ES.datetime <- paste(SF5$ES_TIME2,SF5$ES_DATE,sep=" ")
#3) Transform into Date-Time format
    SF5$ES.datetime2 <- as.POSIXct(SF5$ES.datetime,format="%H%M %y-%m-%d", tz="")

# Did the same for my other time-date of interest
SF5$SH_TIME2<-sprintf("%04d",SF5$SH_TIME) 
SF5$SH.datetime <- paste(SF5$SH_TIME2,SF5$SH_DATE,sep=" ")
SF5$SH.datetime2 <- as.POSIXct(SF5$SH.datetime,format="%H%M %y-%m-%d", tz="")

# Calculate the time difference between the 2 date-time in hours
SF5$duration<-difftime(SF5$SH.datetime2,SF5$ES.datetime2,units="hours",tz="")
于 2012-04-05T16:32:11.630 回答