You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

从Excel导入R时将1810年前日期转为%d-%m-%Y格式的方法

日期格式转换问题求助

在Excel中两列日期格式均为date: *14-03-2012,但导入R后,Date1为POSIXct类型,Date2为字符型。我已能成功转换Date1,但Date2的转换尝试均失败,多次在Stack Overflow查找方案无果,目前通过存入Access再导入R临时解决,希望找到直接从Excel处理的方法。

样本数据

structure(list(ID = c("101", "101", "101", "101", "101", "101", 
"101", "101", "101", "101", "101", "101", "101", "101", "101", 
"101", "101", "101", "101", "101"), AD = c("447", "243", "608", 
"537", "1588", "302", "28", "1035", "755", "8", "1262", "95", 
"1954", "231", "88", "1898", "1028", "669", "103", "773"), Date1 = 
structure(c(1367802000,1324515600, 1404781200, 1391043600, 1621299600, 1340067600, 1291078800,1489453200, 1456966800, 1278986400, 1544058000, 1295398800, 1637629200,1321318800, 1293411600, 1623286800, 1485392400, 1417050000, 1296522000,1431997200), tzone = "UTC", class = c("POSIXct", "POSIXt")), Date2 = c("41400.041666666701", "40913.041666666701",  "41828.041666666701", "41697.041666666701", "44334.041666666701",         "41080.041666666701", "40512.041666666701", "42901.041666666701",         "42443.041666666701", "40372.041666666701", "43535.041666666701",         "40197.041666666701", "44523.041666666701", "40862.041666666701",         "40539.041666666701", "44357.041666666701", "42817.041666666701",         "42016.041666666701", "40575.041666666701", "42143.041666666701")), class = c("tbl_df","tbl", "data.frame"), row.names = c(NA, -20L))

Date1的转换方法(成功)

library("anytime")  
anydate(mydata$Date1)     # 返回格式为yyyy-mm-dd,hh:mm:ss的日期
mydata$Date1 <- substring(mydata$Date1,1,10)     # 移除时分秒部分
mydata$Date1 <- format(as.Date(mydata$Date1,'%Y-%m-%d'),'%d-%m-%Y')
class(mydata$Date1)       # 结果为字符型

Date2的转换失败尝试

  • 套用Date1的转换代码,生成大量NA
  • 使用openxlsx::convertToDateTime(mydata$Date2),因第16行和第20行日期为1809/01/01,出现NAs introduced by coercion警告
  • 使用janitor::excel_numeric_to_date,出现相同的NA警告
  • 使用datetimeutils::convert_date,报错character string is not in a standard unambiguous format

内容的提问来源于stack exchange,提问作者Rara

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.05 00:05:24