Changing date format to “%d/%m/%Y”

旧城冷巷雨未停 提交于 2019-12-17 04:31:35

问题


Would like to change the date format. My data frame is shown below and would like to change all the date formats to "%d/%m/%Y".

df:

id    bdate       wdate        ddate
1   09/09/09    12/10/09     2009-09-27

回答1:


df$ddate <- format(as.Date(df$ddate), "%d/%m/%Y")



回答2:


df$ddate<-strftime(df$ddate,"%d/%m/%Y")
df$bdate<-strftime(strptime(df$bdate,"%d/%m/%y"),"%d/%m/%Y")
df$wdate<-strftime(strptime(df$wdate,"%d/%m/%y"),"%d/%m/%Y")



回答3:


Default R action is to treat strings as factors. Of course, an individual setup may differ from defaults. It's a good practice to change variable values to character, and then convert it to date. I often use chron package - it's nice, simple and what matters the most, it does the job. Only downside of this package lays in time zone handling.

If you don't have chron installed, do:

 install.packages("chron")
 # load it
 library(chron)
 # make dummy data
 bdate <- c("09/09/09", "12/05/10", "23/2/09")
 wdate <- c("12/10/09", "05/01/07", "19/7/07")
 ddate <- c("2009-09-27", "2007-05-18", "2009-09-02")
 # notice the last argument, it will not allow creation of factors!
 dtf <- data.frame(id = 1:3, bdate, wdate, ddate, stringsAsFactors = FALSE)
 # since we have characters, we can do:
 foo <- transform(dtf, bdate = chron(bdate, format = "d/m/Y"), wdate = chron(wdate, format = "d/m/Y"), ddate = chron(ddate, format = "y-m-d"))
 # check the classes
 sapply(foo, class)
 # $id
 # [1] "integer"

 # $bdate
 # [1] "dates" "times"

 # $wdate
 # [1] "dates" "times"

 # $ddate
 # [1] "dates" "times"

C'est ca... it should do the trick...



来源:https://stackoverflow.com/questions/2832385/changing-date-format-to-d-m-y

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!