tags:

views:

244

answers:

1

I'm getting a result I don't understand in R.

If I use strptime with a year and day formatted %Y-%m (like "2009-12"), I get an NA result. But if I add a day, like "2009-12-01", and change the format string accordingly, I do get a result. Example:

> strptime("2009-12",format="%Y-%m")
[1] NA
> strptime("2009-12-03",format="%Y-%m-%d")
[1] "2009-12-03"

Why is that?

Update: The thing I'm curious about is why strptime doesn't parse a year and a month, and the reason it seems weird that it wouldn't do so is because it does parse a year only, or a year-and-a-day:

> strptime("2009",format="%Y") # year only. Works. Uses current month and day as defaults.
[1] "2009-12-02"
> strptime("2009-03",format="%Y-%d") # year and day. Works. Uses current month as default.
[1] "2009-12-03"
> strptime("2009-03",format="%Y-%m") # year and month. Doesn't work. ?
[1] NA
A: 

That seems like sensible behavior to me. As I see it, a better question would be "why does it allow you to do this: strptime("2009-03",format="%Y-%d")?"

Here's a workaround to get what I think you're trying to achieve (i.e. a POSIXlt object with a specified month and year, but today's day):

as.POSIXlt(paste("2009-12", days(Sys.Date()), sep="-"))
Shane
So it's just a weird idiosyncrasy of the language?
bantic
No, its a requirement as a 'date' designates a day in a month in a year, and just a giving a month and a year is not equivalent.
Dirk Eddelbuettel
But then why does it work if you give it only a year, or only a year and a day?
bantic
My guess is that "that's just how it works" (in other words, there is no good reason). As everyone is saying, it doesn't make much sense for why you would actually want to do this at all. If you want today's date, use Sys.Date(). Otherwise just do what Shane suggested above...
griffin