从存储为字符的时间变量中获取时差 [英] Get the time difference from time varaibles stored as character

查看:99
本文介绍了从存储为字符的时间变量中获取时差的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在数据框 start_time stop_time 中有两个字符变量:

I have two character variables in my dataframe start_time and stop_time:

  start_time     stop_time
        <chr>        <chr>   
1     19:5:00     19:11:00 
2    20:33:37     20:34:39
3    20:23:00     20:23:38
4    20:12:00     20:13:00
5    20:00:39     20:00:39

我想根据dplyr的分钟数来计算 start_time stop_time 之间的差异。我的问题是两个变量都表示为字符。

I would like to calculate the difference between start_time and stop_time in terms of minutes with dplyr. My problem is that the two variables are expressed as a character.

预期输出:

    diff_time    
        <dbl>         
1           6     
2         1.2    
3        0.38     
4           1   
5        0.39


推荐答案

library(dplyr)
library(lubridate)

df1 %>% 
  mutate(duration = seconds_to_period(as.numeric(difftime(
                                            strptime(stop_time, "%H:%M:%S"), 
                                            strptime(start_time, "%H:%M:%S"), 
                             units = "secs"))))

#>   start_time stop_time duration
#> 1    19:5:00  19:11:00    6M 0S
#> 2   20:33:37  20:34:39    1M 2S
#> 3   20:23:00  20:23:38      38S
#> 4   20:12:00  20:13:00    1M 0S
#> 5   20:00:39  20:00:39       0S


数据:


Data:

read.table(text="  start_time     stop_time
19:5:00     19:11:00 
20:33:37     20:34:39
20:23:00     20:23:38
20:12:00     20:13:00
20:00:39     20:00:39", stringsAsFactors=F, header=T) -> df1

这篇关于从存储为字符的时间变量中获取时差的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆