Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R Strptime Year and Month with No Delimiter returning NA

Tags:

time

r

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)

like image 966
Kyle Brandt Avatar asked Jul 29 '11 17:07

Kyle Brandt


People also ask

What does strptime do in R?

strptime converts character vectors to class "POSIXlt" : its input x is first converted by as. character . Each input string is processed as far as necessary for the format specified: any trailing characters are ignored. strftime is a wrapper for format.

What is Strptime in C?

Description. The strptime() function converts the character string pointed to by buf to values that are stored in the tm structure pointed to by tm, using the format specified by format. The format contains zero or more directives.

How do I change date format in R?

To format = , provide a character string (in quotes) that represents the current date format using the special “strptime” abbreviations below. For example, if your character dates are currently in the format “DD/MM/YYYY”, like “24/04/1968”, then you would use format = "%d/%m/%Y" to convert the values into dates.

How do I convert a date to a date in R?

You can use the as. Date( ) function to convert character data to dates. The format is as. Date(x, "format"), where x is the character data and format gives the appropriate format.


1 Answers

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

like image 147
Dirk Eddelbuettel Avatar answered Nov 05 '22 22:11

Dirk Eddelbuettel