stackoverflax
stackoverflax

Reputation: 1097

strange R strptime behavior for week of year

Someone please explain this:

strptime(c("2010-01", "2010-02"), format="%Y-%W")
[1] "2010-05-21" "2010-05-21"

Why May 21st? I'm expecting the first and second weeks of the year (01) and (02) to be in January... %W is week of the year, isn't it?

ISOweek2date in the ISOweek package works:

library(ISOweek)
ISOweek2date(c("2010-W01-1", "2010-W02-1"))
[1] "2010-01-04" "2010-01-11"

Upvotes: 3

Views: 153

Answers (2)

leo
leo

Reputation: 141

To get the same results as of ISOweek2date, you should give strptime the same level of details in the time string and format as you did for ISOweek2date.

So adding a "-1" for first day in the week in the time string and -%w in the format string gives you the same result as ISOweek2date:

strptime(c("2010-01-1", "2010-02-1"), format="%Y-%W-%w")
#[1] "2010-01-04" "2010-01-11"

As mentioned above, without enough information you get the current date

Upvotes: 3

thelatemail
thelatemail

Reputation: 93813

Today is (or at least was) May 21. When you don't provide enough information to get an exact day, R decides to fill in using the current datetime values - e.g. -

strptime("2010",format="%Y")
#[1] "2010-05-22 EST"

strptime(c("2010-01", "2010-02"), format="%Y-%W")
#[1] "2010-05-22 EST" "2010-05-22 EST"

Upvotes: 3

Related Questions