首页 > 解决方案 > as.POSIXct 在 r 数据表中给出模棱两可的错误

问题描述

我有一个数据表,其中有一列用于时间戳。我创建了一个名为 date 的新列,使用:setDT(data_test)[,date := as.IDate(ev_date)]

data_test = data_test[,new := as.POSIXct(paste(date, "00:00:00"))]

我收到以下错误:

Error in as.POSIXlt.character(x, tz, ...) : 
  character string is not in a standard unambiguous format

我想找到两个时间戳之间的差异,一个是基于另一个时间戳的日期...例如,如果我的时间戳是 2020-05-18 03:23:45,那么我正在尝试2020-05-18 03:23:45 - 2020-05-18 00:00:00

标签: rdata.table

解决方案


您当然有理由使用实验性日期格式

转换为 POSIXct 是可能的,因为它是您不能使用 HH:MM:SS 的日期

df <- data.frame(ev_date = as.Date('2020-05-18 03:23:45')) %>% as.data.table()
df[,idate := as.IDate(ev_date)][,posix_date := as.POSIXct(idate)]
df
      ev_date      idate posix_date
1: 2020-06-11 2020-06-11 2020-06-11

如果您只想计算两个时间戳之间的差异,则应使用 Datetime 而不是仅使用日期。POSIXct 是通常的标准:

difftime(as.POSIXct('2020-05-18 03:23:45'),as.POSIXct(as.POSIXct('2020-05-18 00:00:00')),unit='hours')
   
Time difference of 3.395833 hours

推荐阅读