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

R语言中Character类型日期时间列转Date格式遇NA问题求助

问题描述
  • 尝试用依赖rJava的read_xlsx()读取xls文件失败,将文件转为csv后用read_csv()成功读取
  • 数据框中Date...Timestamp列为字符型,格式示例:"28/03/2020 17:28"
  • 将该列拆分为Date和Time列后,使用as.Date()、as.POSIXct()等函数转换数据类型时,对应列数据全部变为NA;直接转换原列也失败

数据列类型信息

执行sapply(myDataFrame, class)输出:

Date...Timestamp              DO1              DO2   Controlling.DO               pH 
    "character"        "numeric"        "numeric"        "numeric"        "numeric" 
        Biomass    Titre..mg.mL.      Base.Buffer      Media.Batch 
    "numeric"        "numeric"        "integer"        "integer"

用户拆分代码

#Split Date / Timestamp column by character
myDataFrame <- myDataFrame %>%
                mutate(Date = str_sub(Date...Timestamp, 1,11)) %>%
                mutate(Time = str_sub(Date...Timestamp, 11))
#DataFrame manipulation, drop the old Data Timestamp column
myDataFrame <- myDataFrame %>%
                select(-Date...Timestamp)

用户转换尝试代码

# converting to datetime object
myDataFrame[["Date"]] <- as.POSIXct(myDataFrame[["Date"]], format = "%D/%M/%Y")
myDataFrame[["Time"]] <- as.POSIXct(myDataFrame[["Time"]], format = "%H:%M")
myDataFrame$Date <- as.Date(myDataFrame$Date)
myDataFrame$Time <- as.Date(myDataFrame$Time)
# tried before splitting and splitting afterwards, still error.
myDataFrame$Date...Timestamp <- as.Date(myDataFrame$Date...Timestamp) 
解决方案

错误原因分析

  1. 拆分索引错误:原字符串"28/03/2020 17:28"中,日期部分为前10位,第11位是空格。原代码中str_sub(Date...Timestamp, 1,11)会将空格包含到Date列,导致Date列值为"28/03/2020 "(带尾部空格);Time列从第11位开始会包含前导空格,值为" 17:28",这两种情况都会导致格式匹配失败。
  2. 格式字符串错误:
    • %D是%m/%d/%y的简写(月/日/两位年份),与你的日/月/四位年份格式不符;
    • %M代表分钟,月份应该用小写的%m;
    • as.Date()仅处理日期部分,无法转换纯时间字符串,用它转换Time列必然失败。

修正后的代码

1. 修正拆分逻辑

library(dplyr)
library(stringr)

# 提取日期部分(前10位),提取时间部分并去除前导空格
myDataFrame <- myDataFrame %>%
  mutate(Date = str_sub(Date...Timestamp, 1, 10),
         Time = str_trim(str_sub(Date...Timestamp, 12))) %>%
  select(-Date...Timestamp)

2. 转换数据类型

# 转换Date列为Date类型,格式为日/月/四位年
myDataFrame$Date <- as.Date(myDataFrame$Date, format = "%d/%m/%Y")

# 转换Time列为纯时间类型,推荐使用hms包
library(hms)
myDataFrame$Time <- as_hms(myDataFrame$Time)

# 可选:直接将原列转换为完整的POSIXct时间戳(无需拆分)
# myDataFrame$DateTime <- as.POSIXct(myDataFrame$Date...Timestamp, format = "%d/%m/%Y %H:%M")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 15:20:22