Convert date from yyyy-mm-dd to mm/dd/yyyy h:mm:ss in R

后端 未结 2 1653
北海茫月
北海茫月 2021-01-26 20:55

My data contains some date fields in this format yyyy-mm-dd

    id <- c(1,2,3,4,5)
    d1 <- c(\"2001-01-01\", \"1999-12-01\",\"2007-11-31\", \"1995-05-01\         


        
2条回答
  •  清歌不尽
    2021-01-26 21:35

    Just use strptime (or as.Date) and format:

    > format(strptime(datadd$d1, format = "%Y-%m-%d"), "%m/%d/%Y %H:%M:%S")
    [1] "01/01/2001 00:00:00" "12/01/1999 00:00:00" "11/13/2007 00:00:00"
    [4] "05/01/1995 00:00:00" "01/07/2013 00:00:00"
    
    ## format(as.Date(datadd$d1), "%m/%d/%Y %H:%M:%S")
    

    I suppose you can use some gsub too if you want to remove the leading zeroes for single digit days and months.

提交回复
热议问题