【问题标题】:How to change date format to 2019-Feb-07 to 2019-02-07 in R?如何在 R 中将日期格式更改为 2019-Feb-07 到 2019-02-07?
【发布时间】:2022-01-10 13:19:10
【问题描述】:

我有一个从 .txt 文件中读取数据的代码,其中有一个日期列 dd/mm/yyyy 和时间列 HH:MM:SS,我想将这些列合并到一个日期时间列 yyyy /mm/dd HH:MM:SS。

数据框结构为:

structure(list(V1 = c("05/02/2019", "07/02/2019", "08/02/2019", 
"09/02/2019", "10/02/2019", "11/02/2019", "12/02/2019", "13/02/2019"
),
V2 = c("10:37:34", "00:00:00", "00:00:00", "00:00:00", "00:00:00", 
"00:00:00", "00:00:00", "00:00:00"), 
V3 = c("0,2", "0", "0", 
"0", "0", "0", "0", "0"), 
V4 = c("NEW-BLOCK", "NEW-DAY", "NEW-DAY", 
"NEW-DAY", "NEW-DAY", "NEW-DAY", "NEW-DAY", "NEW-DAY"), 
V5 = c("", 
"", "", "", "", "", "", ""), 
V6 = c("", "", "", "", "", "", "", 
"")), row.names = 5:12, class = "data.frame")

我的工作代码是:

importeddataframe <-read.table(k,fill =TRUE, stringsAsFactors =FALSE )

importeddataframe$V1<-chron(importeddataframe$V1, importeddataframe$V2, format =c(dates="d/m/y", times="h:m:s"))
importeddataframe$V1<-chron(importeddataframe$V1, importeddataframe$V2, format =c(dates="yyyy-mm-dd", times="H:M:S"))

其中 k 是路径源,V1 是日期列,V2 是时间列,我正在尝试使用 chron 将 V1 重新定义为日期时间列。我设法为日期和时间设置了正确的格式,除了一个细节:月份始终是缩写而不是数字。所以二月是二月而不是 02,十月是十月而不是 10,等等。

chron 函数中是否有需要更改的参数?是否还有其他函数不会为时间创建书面缩写?

感谢大家的帮助!

【问题讨论】:

  • 如果你能创建一个可重现的例子那就太好了,例如通过dput 显示importeddataframe 的示例。
  • @JKupzig 我已经包含了 dput(importeddataframe) 的返回,只有列 V1 和 V2 是感兴趣的。这有帮助吗?

标签: r datetime chron


【解决方案1】:

使用计时:

importeddataframe$V1<-chron::chron(importeddataframe$V1, importeddataframe$V2, format =c(dates="d/m/y", times="h:m:s"), out.format=c(dates="y-m-d", times="H:M:S"))
> importeddataframe$V1
[1] (19-02-05 10:37:34) (19-02-07 00:00:00) (19-02-08 00:00:00) (19-02-09 00:00:00) (19-02-10 00:00:00) (19-02-11 00:00:00) (19-02-12 00:00:00)
[8] (19-02-13 00:00:00)

使用基础 R

importeddataframe$Time <- as.POSIXct(paste(importeddataframe$V1,importeddataframe$V2), format="%d/%m/%Y %H:%M:%S" )
> importeddataframe$Time
[1] "2019-02-05 10:37:34 CET" "2019-02-07 00:00:00 CET" "2019-02-08 00:00:00 CET" "2019-02-09 00:00:00 CET" "2019-02-10 00:00:00 CET"
[6] "2019-02-11 00:00:00 CET" "2019-02-12 00:00:00 CET" "2019-02-13 00:00:00 CET"

【讨论】:

  • 谢谢@JKupzig,基本的 R 解决方案工作得很好!
猜你喜欢
  • 1970-01-01
  • 2014-09-23
  • 2020-03-07
  • 2019-11-10
  • 1970-01-01
  • 2020-01-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多