as.POSIXct.numerictime1,tz = tz中的错误:必须提供“原点”

问题描述

我每天为小时和分钟(1:00、2:00,...,13:30,...,22:30、24:10)分配时间表的开始和结束时间, 在那之后,我想将它们之间的小时数相去。

这是我的尝试:

# intial string example #

df[1,"schedule"] 

 // console output//
"14:00H ÀS 22:18H - 1H DE DESCANSO"

## setting hour and minutes format ##
initial_hour <- hm(
                    as.character(
                    factor(
                    substr(
                    df$schedule,start = 1,stop  = 5)
                    )))

final_hour <-   hm(
                    as.character(
                    factor(
                    substr(
                    df$schedule,start = 11,stop =  15))))

# hour difference ##
difftime(final_hour,initial_hour,tz = Sys.timezone(location = TRUE),units = "hours")

// console output //

Error in as.POSIXct.numeric(time1,tz = tz) : 'origin' must be supplied

是否可以在参数函数中设置“原点”?

解决方法

由于您似乎正在使用lubridate,因此可以减去不含difftime的句点:

h1 <- lubridate::hm('24:10')
h2 <- lubridate::hm('23:05')

h1-h2

#> [1] "1H 5M 0S"

reprex package(v0.3.0)于2020-09-25创建

,

将其放入数据框并使用dplyrlubridate

library(dplyr)
library(lubridate)

df %>%
   mutate(time_difference =
             hm(
                substr(schedule,start = 11,stop  = 15)
             ) - 
             hm(
                substr(schedule,start = 1,stop  = 5)
             ))

#> Note: method with signature 'Period#ANY' chosen for function '-',#>  target signature 'Period#Period'.
#>  "ANY#Period" would also be valid

#>                            schedule time_difference
#> 1 14:00H ÀS 22:18H - 1H DE DESCANSO       8H 18M 0S
#> 2 18:00H ÀS 16:18H - 1H DE DESCANSO      -2H 18M 0S

您的输入项,再加上一项数据

df <- data.frame(
   schedule = c("14:00H ÀS 22:18H - 1H DE DESCANSO","18:00H ÀS 16:18H - 1H DE DESCANSO")
)