1

I have a series of dates and am trying to get the week of the year. This seems to be innacurate.

Order_Date = c("2017-06-10","2017-06-11","2017-06-12","2017-06-13",
               "2017-06-14","2017-06-15","2017-06-16")
strftime(as.POSIXlt(Order_Date) ,format="%W")
week(Order_Date)

06/10 was a saturday and so there's no way that 06/10 and 06/11 were of the same week.

Any ideas on how to get this?

ATMA
  • 1,450
  • 4
  • 23
  • 33

1 Answers1

2

Working with date-time is not always straightforward. An illustration of your question and the comments from SO members. I added a few days to make the point more clear.

library(lubridate)
Order_Date = c("2017-06-10","2017-06-11","2017-06-12","2017-06-13",
               "2017-06-14","2017-06-15","2017-06-16", "2017-06-17",
               "2017-06-18", "2017-06-19")
strftime(as.POSIXlt(Order_Date) ,format="%W") # week starts on Monday
#  [1] "23" "23" "24" "24" "24" "24" "24" "24" "24" "25"

strftime(as.POSIXlt(Order_Date) ,format="%U") # week starts on Sunday
#  [1] "23" "24" "24" "24" "24" "24" "24" "24" "25" "25"

week(Order_Date) # week starts on Sunday
#  [1] 23 24 24 24 24 24 24 24 25 25

In a related question: here, I used @UweBlock 's ISOweek package to circumvent problems with year-ends after extensive testing. Here is the code:

library(ISOweek)
library(stringr)
str_replace(ISOweek(Order_Date), "201.-W", "")  # week starts on Monday (and follows ISO 8601)
#  [1] "23" "23" "24" "24" "24" "24" "24" "24" "24" "25"

You can get more information with ?ISOweek.

Please let me know whether this is what you want.

KoenV
  • 4,113
  • 2
  • 23
  • 38