如何计算每月的时差?

时间:2018-11-09 13:10:40

标签: r time difference monthcalendar

一个简单的问题:

# Given the following initial time
t0 <- strptime('17/Nov/2010:08:04:21',format='%d/%b/%Y:%H:%M:%S')
# ...and final time
t1 <- strptime('21/Jan/2011:13:11:04',format='%d/%b/%Y:%H:%M:%S')
# I can calculate the difference of time
difftime(t1,t0,units='hours')
# Time difference of 1565.112 hours

但是,我也想知道分别与11月,12月和1月对应的小时数。当然,我必须对不同年份的数千个数据进行处理,但是循环不是我的问题。任何想法?谢谢!

3 个答案:

答案 0 :(得分:3)

这是您的意思吗?这是一个以每月差异为例的示例:

year

这为您提供了月份界限:

t0 <- strptime('17/Nov/2010:08:04:21',format='%d/%b/%Y:%H:%M:%S')
t1 <- strptime('21/Jan/2011:13:11:04',format='%d/%b/%Y:%H:%M:%S')

seq.firsts <- seq.Date(as.Date(t0),as.Date(t1),by='month')
boundaries <- paste0(format(seq.firsts, "%Y-%m"),"-01")

但是现在您必须将它们整理好,如果它们进入> boundaries [1] "2010-11-01" "2010-12-01" "2011-01-01" 之前,请将它们扔掉:

t0

现在您可以在列表中的每一对之间timelist <- c(t0,t1,boundaries) ab <- sort( timelist[timelist >= t0] ) # adjust boundaries; throw out beyond t0 and t1

difftime

或添加单位:

> for (i in 1:(length(ab)-1)) { print(abs(  difftime(ab[i],ab[i+1])   ))  }
Time difference of 81.59102 days
Time difference of 30.04167 days
Time difference of 31 days

答案 1 :(得分:1)

您可以利用as.POSIXct()进行秒计算。

# create a time vector 
sec <- seq(1, as.numeric(dif)*3.6e3, length.out=dif)

# create time table
t.dif.1 <- table(strftime(as.POSIXct(sec, origin=t0), format="%Y-%m"))
t.dif.1 <- rbind(hours=t.dif.1, "cumulated hours"=cumsum(t.dif.1)) # add cumulated hours

产量

> t.dif.1
                2010-11 2010-12 2011-01
hours               327     744     495
cumulated hours     327    1071    1566

答案 2 :(得分:1)

类似的事情会起作用:

   d <- force_tz(seq(t0, t1, by="month"), tzone ="EST")

  Start<- list.append(d[[1]], lapply(d[2:length(d)], function(e) floor_date(e,"month")))

  #there is probably a cleaner way to do the next step than using  double 
  #rev() but it is get around some issues with unlist and lossing my datetime format

      End<- rev(list.append(d[[length(d)]], lapply(rev(d)[2:length(d)], function(e) ceiling_date(e,"month"))))
      df<-data.frame(Start ,End )
      df$diff<- difftime(df$End, df$Start, units ="days")
      df$diff_hours <- difftime(df$End, df$Start, units ="hours")
  df

                Start                 End          diff     diff_hours
1 2010-11-17 08:04:21 2010-12-01 00:00:00 13.66365 days 327.9275 hours
2 2010-12-01 00:00:00 2011-01-01 00:00:00 31.00000 days 744.0000 hours
3 2011-01-01 00:00:00 2011-01-17 08:04:21 16.33635 days 392.0725 hours