将日期时间变量从 Excel 正确格式化为 R

Properly Format Datetime variable from Excel to R

我在格式化最初来自 Excel:

的日期时间变量时遇到困难

使用带有 detectDates = FALSE 选项的包 openxlsx 从 Excel 读取数据。在原始 Excel 文件中,它们看起来像这样:

udate       utime
1/30/2015   4:48:44 PM
1/29/2015   4:17:23 PM

这就是它们在使用 detectDates = FALSE

导入 R 时的样子
#-----------------------------------------------------------------------------------------#
# EXAMPLE DATA
#-----------------------------------------------------------------------------------------#
udate <- c(42034, 42033)
utime <- c(0.7005093, 0.6787384)

#-----------------------------------------------------------------------------------------#
# FORMAT DATE
#-----------------------------------------------------------------------------------------#
udate <- as.Date(udate - 25569, origin = "1970-01-01")

> udate
[1] "2015-01-30" "2015-01-29"

#-----------------------------------------------------------------------------------------#
# FORMAT TIME
#-----------------------------------------------------------------------------------------#
utime <- as.POSIXct((utime - 25569) * 86400, tz="GMT", origin="1970-01-01")

> utime
[1] "1899-12-30 16:48:45 GMT" "1899-12-30 16:17:23 GMT"

如您所见,时间无法完全正常工作(即时间的日期部分无法正常工作)。 我怎样才能正确地拥有一个具有正确日期和时间的变量?似乎简单地加上 116 年就可以解决问题,但我知道这不是那么简单,因为我怀疑日期时间格式是以毫秒为单位的。

没有时间对象。 POSIXct 是日期时间 class,即必须包含日期和时间。

as.POSIXct(
  as.POSIXlt(
    as.Date(udate, origin = "1899-12-30"), #see ?as.Date
    tz = "GMT"), 
  tz = "GMT") + utime * 3600 * 24
#[1] "2015-01-30 16:48:44 GMT" "2015-01-29 16:17:22 GMT"

由于 DST 或闰秒等有趣的事情,没有日期的时间不起作用。