如何计算每月时间差?

4
一个简单的问题:
# 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月分别对应多少小时。当然,我需要对来自不同年份的成千上万个数据进行这样的操作,但循环不是我的问题。有什么建议吗?谢谢!


你能否稍微清楚一下你需要的输出是什么? - sai saran
3个回答

3

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

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

或者添加单位:

> for (i in 1:(length(ab)-1)) { print(abs(  difftime(ab[i],ab[i+1],units='hours')   ))  }
Time difference of 1958.184 hours
Time difference of 721 hours
Time difference of 744 hours

这正是我正在寻找的...谢谢! - rpaolo1967 RP
1
@mysteRious,我认为你的代码可能存在一个错误。由于我们正在查看从本月初到1月21日的天数,因此“31天的时间差”是不正确的。 - Jrakru56

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

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

对于那些感兴趣的人,unlist问题在这里讨论:https://dev59.com/F2Uo5IYBdhLWcg3w7jEq - Jrakru56

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接