如何计算R中日期之间的差异?[重复]

wpx232ag  于 2023-11-14  发布在  其他
关注(0)|答案(1)|浏览(113)

这个问题已经有答案了

Get date difference in years (floating point)(7个回答)
14天前关闭
我的df有两列需要处理。我想计算这两列的差。做了半天,没有成功。
started_at和ended_at,下面是一个例子:
第一个月
它们是char类型的。我设法把它们转换成了POSIX:
df$started_at <- ymd_hms(df$started_at)
df$ended_at <- ymd_hms(df$ended_at)
我需要的是两个值之间的时间差。有人能帮助我吗?
我尝试使用以下方法,我得到:* 字符串不是标准的明确格式 *

difftime(scrap_3$ended_at, scrap_3$started_at, units="mins")

字符串
谢谢你,谢谢!

yebdmbv4

yebdmbv41#

lubridate有一个很好的方法来做到这一点。

library(dplyr)
library(lubridate)

df <-
  data.frame(
           started_at = c("2023-09-23 00:27:50",
                          "2023-09-02 09:26:43","2023-09-25 18:30:11",
                          "2023-09-13 15:30:49","2023-09-18 15:58:58","2023-09-15 20:19:25"),
             ended_at = c("2023-09-23 00:33:27",
                          "2023-09-02 09:38:19","2023-09-25 18:41:39",
                          "2023-09-13 15:39:18","2023-09-18 16:05:04","2023-09-15 20:30:27")
         )

mutate(
  df,
  started_at = ymd_hms(started_at),
  ended_at = ymd_hms(ended_at),
  diff = ended_at - started_at
)
#>            started_at            ended_at           diff
#> 1 2023-09-23 00:27:50 2023-09-23 00:33:27  5.616667 mins
#> 2 2023-09-02 09:26:43 2023-09-02 09:38:19 11.600000 mins
#> 3 2023-09-25 18:30:11 2023-09-25 18:41:39 11.466667 mins
#> 4 2023-09-13 15:30:49 2023-09-13 15:39:18  8.483333 mins
#> 5 2023-09-18 15:58:58 2023-09-18 16:05:04  6.100000 mins
#> 6 2023-09-15 20:19:25 2023-09-15 20:30:27 11.033333 mins

字符串
创建于2023-10-30使用reprex v2.0.2

相关问题