1

我有一些从 Python 导出的 timedelta 字符串。我正在尝试将它们导入以在 R 中使用,但我得到了一些奇怪的结果。

当时间增量很小时,我得到的结果会相差 2 天,例如:

> as.difftime('26 days 04:53:36.000000000',format='%d days %H:%M:%S.000000000')

Time difference of 24.20389 days

当它们更大时,它根本不起作用:

> as.difftime('36 days 04:53:36.000000000',format='%d days %H:%M:%S.000000000')
Time difference of NA secs
4

1 回答 1

1

26 days 04:53:36.000000000我还读入了“R”一些时间增量对象,我用“Python”处理过,格式也有类似的问题。正如 Gregor 所说, %d instrptime是一个月中的一天,作为一个零填充的十进制数,因此不适用于 >31 的数字,并且似乎没有累积天数的选项(可能是因为strptime日期时间对象和不是时间增量对象)。

我的解决方案是将对象转换为字符串并按照 Gregor 的建议提取数值数据,我使用该gsub函数进行了此操作。

# convert to strings
data$tdelta <- as.character(data$tdelta)
# extract numerical data
days <- as.numeric(gsub('^.*([0-9]+) days.*$','\\1',data$tdelta))
hours <- as.numeric(gsub('^.*ys ([0-9]+):.*$','\\1',data$tdelta))
minutes <- as.numeric(gsub('^.*:([0-9]+):.*$','\\1',data$tdelta))
seconds <- as.numeric(gsub('^.*:([0-9]+)..*$','\\1',data$tdelta))
# add up numerical components to whatever units you want
time_diff_seconds <- seconds + minutes*60 + hours*60*60 + days*24*60*60
# add column to data frame
data$tdelta <- time_diff_seconds 

这应该允许您使用时差进行计算。希望有帮助。

于 2016-08-12T04:03:37.507 回答