0

Here mydata

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))

I use mdy function from lubridate

ga$Date=mdy(ga$Date)

So I get only NA. How can i get such output format(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
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
psysky
  • 3,037
  • 5
  • 28
  • 64

3 Answers3

3

We can use:

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

The above will return a character representation of the date, if you want to keep as date(I find the display somewhat misleading), you could use:

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"

Perhaps mdy defaults to this kind of representation as shown here.

NelsonGon
  • 13,015
  • 7
  • 27
  • 57
3

We can use base R to get output in required format

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
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
3

We can use anydate from anytime

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"

If we want to convert a date time format

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"
akrun
  • 874,273
  • 37
  • 540
  • 662