12

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

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

From help strptime:

%Y Year with century
%m Month as decimal number (01–12)

Kyle Brandt
  • 23,178
  • 32
  • 115
  • 158
  • 1
    You found the documentation bug with *`strptime`* that year-month-day must all be supplied, which is never stated anywhere: *"For strptime the input string need not specify the date completely: it is assumed that unspecified seconds, minutes or hours are zero, and an unspecified year, month or day is the current one."* – smci Jun 17 '12 at 16:24
  • thanks for this comment. Even more strange: when doing that only with "%Y" (on my computer) it automatically add "12-27" for month and day and return a valide value. But when trying "%Y-%m" it return `NA`. this started to drive me crazy. – Simon C. Dec 27 '18 at 09:29

1 Answers1

16

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).

Dirk Eddelbuettel
  • 331,520
  • 51
  • 596
  • 675
  • so in R you can not say that there is no day digit, you have to inject the assumption of 01. strange. – userJT Apr 17 '12 at 21:12