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

后端 未结 2 1648
北海茫月
北海茫月 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.

    0 讨论(0)
  • 2021-01-26 21:44

    the lubridatepackage is your friend. It's really intuitive.

    ## install and launch the {lubridate} package
    > dt <- "1/1/2001 0:10:00"  
    > dt2 <- mdy_hms(dt)
    [1] "2001-01-01 00:10:00 UTC"
    
    0 讨论(0)
提交回复
热议问题