无法将 yymmdd 转换为 mmddyy

Can't convert yymmdd to mmddyy

这里是我的数据

ga=structure(list(Date = c(190410L, 190410L, 190410L, 190410L, 190410L
), open = c(162.4, 162.57, 162.94, 162.87, 162.96), high = c(162.57, 
162.94, 162.95, 163, 163.11), low = c(162.12, 162.51, 162.83, 
162.83, 162.95), close = c(162.57, 162.94, 162.9, 162.95, 162.95
)), class = "data.frame", row.names = c(NA, -5L))

我使用 lubridate

中的 mdy 函数
ga$Date=mdy(ga$Date)

所以我只得到 NA。 我怎样才能得到这样的输出格式(mm.dd.yy)

    Date        open   high    low  close
1   04.10.2019 162.40 162.57 162.12 162.57
2   04.10.2019 162.57 162.94 162.51 162.94
3   04.10.2019 162.94 162.95 162.83 162.90
4   04.10.2019162.87 163.00 162.83 162.95
5   04.10.2019 162.96 163.11 162.95 162.95

我们可以使用:

strftime(lubridate::ymd(ga$Date),"%m %d %Y")
[1] "04 10 2019" "04 10 2019" "04 10 2019" "04 10 2019" "04 10 2019"

上面将return日期的字符表示,如果你想保留日期(我觉得显示有点误导),你可以使用:

lubridate::mdy(strftime(lubridate::ymd(ga$Date),"%m %d %y"))
[1] "2019-04-10" "2019-04-10" "2019-04-10" "2019-04-10" "2019-04-10"

也许mdy默认为这种表示形式,如图here

我们可以使用 base R 来获得所需格式的输出

ga$Date <- format(as.Date(as.character(ga$Date), "%y%m%d"), "%m.%d.%Y")

ga
#        Date   open   high    low  close
#1 04.10.2019 162.40 162.57 162.12 162.57
#2 04.10.2019 162.57 162.94 162.51 162.94
#3 04.10.2019 162.94 162.95 162.83 162.90
#4 04.10.2019 162.87 163.00 162.83 162.95
#5 04.10.2019 162.96 163.11 162.95 162.95

我们可以使用 anytime

中的 anydate
library(anytime)
format(anydate(as.character(ga$Date)), "%m.%d.%Y")
#[1] "04.10.2019" "04.10.2019" "04.10.2019" "04.10.2019" "04.10.2019"

如果我们要转换日期时间格式

str1 <- "190410;100000"
format(as.POSIXct(str1, format= "%y%m%d;%H%M%S"), "%m.%d.%Y %H:%M")
#[1] "04.10.2019 10:00"