开发者

Why is parsing "%Y-%m" using strptime in R giving an NA result, but "%Y-%m-%d" works? [duplicate]

开发者 https://www.devze.com 2022-12-13 11:03 出处:网络
This question already has answers here: Converting year and month ("yyyy-mm" format) to a date?
This question already has answers here: Converting year and month ("yyyy-mm" format) to a date? (9 answers) Closed 7 years ago.

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. Work开发者_如何学JAVAs. 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

Update to explain why this is not a duplicate The possible duplicate was asked a few years after this question and it is concerned with a separate API in R: the asDate function. This question is about a quirk of the strptime function that as of R 3.1.3 still applies.


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="-"))


I'm just guessing here. But if it takes a year and a day, it's probably taking a year and a day in the range of 1-365 (or 366 for leap years). What you could do is use paste() and add -01 at the end to get the standard YYYY-MM-DD format.

Here's the test I ran.

strptime("2009-123",format="%Y-%d")

returns "2009-05-12"

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号