【问题标题】:How to convert date and time into a duration column in excel in R如何在R中的excel中将日期和时间转换为持续时间列
【发布时间】:2019-10-31 18:12:07
【问题描述】:

我想用

在 excel 中取一列
1   1/1/19 5:20
2   1/1/19 5:30 
3   1/1/19 5:38 
4   1/1/19 5:52 
5   1/1/19 6:00 
6   1/1/19 6:00
7   1/1/19 6:00 
8   1/1/19 6:15 

进入第一个数字为的持续时间列

0 
.167 
.3
.53
.66
.66
.66
.91

距离我第一次已经过去了 10 分钟 我有一整列我想转换到不同的日子和不同的月份,然后当我们到达底部时,我希望它说 90000 小时,或者说自 1 日凌晨 5:20 以来已经过去了多少小时

【问题讨论】:

标签: r time lubridate duration


【解决方案1】:

几个步骤。首先,一些示例数据:

dat <- read.csv(header = FALSE, stringsAsFactors = FALSE, text="
1/1/19 5:20
1/1/19 5:30
1/1/19 5:38
1/1/19 5:52
1/1/19 6:00
1/1/19 6:00
1/1/19 6:00
1/1/19 6:15")
dat
#            V1
# 1 1/1/19 5:20
# 2 1/1/19 5:30
# 3 1/1/19 5:38
# 4 1/1/19 5:52
# 5 1/1/19 6:00
# 6 1/1/19 6:00
# 7 1/1/19 6:00
# 8 1/1/19 6:15

其次,将其转换为“正确的”POSIXt(时间戳)对象:

dat$V1 <- as.POSIXct(dat$V1, format = "%m/%d/%y %H:%M", tz = "UTC")
dat
#                    V1
# 1 2019-01-01 05:20:00
# 2 2019-01-01 05:30:00
# 3 2019-01-01 05:38:00
# 4 2019-01-01 05:52:00
# 5 2019-01-01 06:00:00
# 6 2019-01-01 06:00:00
# 7 2019-01-01 06:00:00
# 8 2019-01-01 06:15:00

接下来,找出不同之处。请注意,差分可能返回的单位不是秒,因此防御性编程可能强制

d <- dat$V1 - dat$V1[1]
d
# Time differences in secs
# [1]    0  600 1080 1920 2400 2400 2400 3300

units(d) <- "hours"
d
# Time differences in hours
# [1] 0.0000000 0.1666667 0.3000000 0.5333333 0.6666667 0.6666667 0.6666667
# [8] 0.9166667

或根据@akrun 的建议,一次调用

difftime(dat$V1, dat$V1[1], units="hours")
# Time differences in hours
# [1] 0.0000000 0.1666667 0.3000000 0.5333333 0.6666667 0.6666667 0.6666667
# [8] 0.9166667

【讨论】:

  • 另一个选项 difftime library(dplyr);library(lubridate);&gt; dat %&gt;% mutate(V1 = mdy_hm(V1), V2 = difftime(V1, first(V1), unit = 'hour'))
猜你喜欢
  • 2020-03-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-15
  • 2020-12-07
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多