CSV导入时间

时间:2019-06-10 04:47:16

标签: r duration

我有一个CSV文件,其中包含要导入R的通话记录,例如通话时间,被叫号码,通话时间等。

CSV文件中“通话时间”字段的格式类似于1d02:03:04,即1天2小时3分4秒。

我可以使用df.duration = pd.to_timedelta(df.duration)在Python Pandas中轻松地将Duration字段转换为Duration对象。 转换后,我可以通过将开始时间与持续时间相加来获得停止时间。

我正在寻找R中的等效项,以将1d02:03:04转换为持续时间对象,以便获得结束时间。

2 个答案:

答案 0 :(得分:0)

或者,您也可以为此使用regex(即使其他解决方案,例如lubridate可能会更好):

首先创建模式^(\\d*)d(\\d*):?(\\d*):?(\\d*)$(可能需要调整格式)以提取持续时间的天,小时,分钟和秒。然后,使用此信息,您可以添加开始时间。

fun = function (start_time, duration) {
  # Check start_time
  if (!'POSIXct' %in% class(start_time))
    stop('Expect "start_time" to be of class "POSIXct"')

  # Regex pattern for extraction of days, hours, minutes & seconds
  pattern = '^(\\d*)d(\\d*):?(\\d*):?(\\d*)$'

  # Extract data
  days    = as.integer(gsub(pattern, '\\1', duration))
  hours   = as.integer(gsub(pattern, '\\2', duration))
  minutes = as.integer(gsub(pattern, '\\3', duration))
  seconds = as.integer(gsub(pattern, '\\4', duration))
  # Maybe add some safety measures just in case e.g. ifelse(is.na(seconds ), 0L, seconds)

  # Add (in seconds)
  final_time = start_time + seconds + minutes*60 + hours*60*60 + days*60*60*24
  return (final_time)
}

这是一个带有向量的小例子

durations = c('1d02:03:04', '2d02:03:04', '10d02:03:04')
start_times = rep(Sys.time(), 3L)
fun(start_time = start_times, duration = durations)
# [1] "2019-06-11 11:02:19 CEST" "2019-06-12 11:02:19 CEST" "2019-06-20 11:02:19 CEST"

答案 1 :(得分:0)

chron times类将持续时间表示为几天和一天的一部分。我们定义了两个函数,以从我们的自定义文本格式转换为times,并从times转换为我们的自定义文本格式。

library(chron)
text2times <- function(x) with(read.table(text = as.character(x), sep = "d", as.is = TRUE),
  V1 + times(V2))
times2text <- function(x) paste(as.integer(x), format(x %% 1), sep = "d") 

dd <- transform(d, diffdays = text2times(stop) - text2times(start),
                   difftext = times2text(text2times(stop) - text2times(start)))

给予:

       start       stop diffdays   difftext
1 1d02:03:04 2d02:03:50 1.000532 1d00:00:46

S3自定义类dur

这可能对您所需要的功能来说是过高的,但是我们可以定义一个S3类dur来实现。

as.dur <- function(x, ...) UseMethod("as.dur")
as.dur.character <- function(x, ...) structure(text2times(x), class = c("dur", "times"))
as.dur.factor <- function(x, ...) as.dur(as.character(x))
format.dur <- function(x, ...) times2text(times(x))

# new it's easy
transform(d, diff = as.dur(stop) - as.dur(start))

给予:

       start       stop       diff
1 1d02:03:04 2d02:03:50 1d00:00:46

在read.table中使用dur

我们还可以直接将数据读入dur

setAs("character", "dur", function(from) as.dur(from))

# test input - normally read from file but to keep answer self contained use string
Lines <- "start stop
1d02:03:04 2d02:03:50"

# now it's even easier
dd <- read.table(text = Lines, header = TRUE, colClasses = c("dur", "dur"))
transform(dd, diff = stop - start)
##        start       stop       diff
## 1 1d02:03:04 2d02:03:50 1d00:00:46

注意

以可重复形式输入的样本:

d <- data.frame(start = "1d02:03:04", stop = "2d02:03:50")