R Strptime Year and Month with No Delimiter returning NA

前端 未结 1 1662
面向向阳花
面向向阳花 2021-01-02 02:56

I\'m probably doing something stupid and not seeing it, but:

> strptime(\"201101\",\"%Y%m\")
[1] NA

From help strptime:

相关标签:
1条回答
  • 2021-01-02 03:08

    Just paste a day field (say, "01") that you ignore:

    R> shortdate <- "201101"
    R> as.Date(paste(shortdate, "01", sep=""), "%Y%m%d")
    [1] "2011-01-01"
    R> 
    

    I prefer as.Date() for dates and strptime() for POSIXct objects, i.e. dates and times.

    You can then convert the parsed Date object into a POSIXlt object to retrieve year and month:

    R> mydt <- as.Date(paste(shortdate, "01", sep=""), "%Y%m%d")
    R> myp <- as.POSIXlt(mydt)
    R> c(myp$year, myp$mon)
    [1] 111   0
    R> 
    

    This is standard POSIX behaviour with years as "year - 1900" and months as zero-indexed.

    Edit seven years later: For completeness, and as someone just upvoted this, the functions in my anytime package can help:

    R> anytime::anydate("201101")    ## returns a Date
    [1] "2011-01-01"
    R> anytime::anytime("201101")    ## returns a Datetime
    [1] "2011-01-01 CST"
    R> 
    

    The use a different parser (from Boost Date_time which is more generous and imputes the missing day (or day/hour/minute/second in the second case).

    0 讨论(0)
提交回复
热议问题