代码之家  ›  专栏  ›  技术社区  ›  Edward

使用不同类型的时间格式将字符串转换为日期

  •  0
  • Edward  · 技术社区  · 10 年前

    我有一个如下的数据帧

    library(lubridate) 
    Date <- c("18.11.2016 21:03:41", "19.11.2016", "20.11.2016","21.11.2016")
    df = data.frame(Date) 
    df
    

    我想得到

    df$Date
    [1] "2016-11-18" "2016-11-19" "2016-11-20" "2016-11-21"
    

    &

    df$Date = dmy(df$Date)
    

    我明白了

    Warning message:
     1 failed to parse. 
    

    如何修复它?

    1 回复  |  直到 10 年前
        1
  •  0
  •   Pritam Banerjee Ashish Karnavat    10 年前

    试试这个:

    s <- c("2004-03-21 12:45:33.123456",    # ISO
           "2004/03/21 12:45:33.123456",    # variant
           "20040321",                      # just dates work fine as well
           "Mar/21/2004",                   # US format, also support month abbreviation or full
           "rapunzel")                      # will produce a NA
    
    p <- toPOSIXct(s)
    
    options("digits.secs"=6)                # make sure we see microseconds in output
    print(format(p, tz="UTC")
    

    阅读更多 here .

    推荐文章