How to find the interval between two dates that are in year and week format. Example 201630 and 201851
Asked
Active
Viewed 55 times
1 Answers
1
As @thelatemail pointed out if you have week number you also need day of the week to get the date. We can use %U
to identify week number and %u
to get day of the week. We use an arbitrary day of the week (here 1).
d1 <- as.character(201630)
d2 <- as.character(201851)
diff(as.Date(paste0(c(d1,d2),"1"), format="%Y%U%u"))
#Time difference of 882 days
Of if you need output in another unit we can also use difftime
difftime(as.Date(paste0(d2, 1), "%Y%U%u"),
as.Date(paste0(d1, 1), "%Y%U%u"), units = "weeks")

Ronak Shah
- 377,200
- 20
- 156
- 213
-
1I'd check the output of those `as.Date()` calls. I don't think they're right because those source dates aren't exactly 2 years apart. – thelatemail Jul 15 '19 at 09:57
-
Stealing from the potential duplicate, I think you need something like `diff(as.Date(paste0(c(d1,d2),"1"), format="%Y%U%u"))` – thelatemail Jul 15 '19 at 10:05
-
1@thelatemail ahh okay..so it also needs day of the week to correctly get the date when using week number. Makes sense.I'll update. – Ronak Shah Jul 15 '19 at 10:10
-
@YashodaSingh which code are you using? Can you also share `dput(head(df))` where `df` is your dataframe name so that it is easy to reproduce your issue? – Ronak Shah Jul 15 '19 at 10:27
-
Hey @RonakShah I am trying to mutate a column where I can have the difference of Original date and returning date that are in year and week format. I tried mutating columns and used your codes but failed. test <- as.character(Customer_Retention_a$ORIGINAL_WEEK) test1 <- as.character(Customer_Retention_a$RETURNING_WEEK) A <- difftime(as.Date(paste0(test1, 1), "%Y%U%u"), as.Date(paste0(test, 1), "%Y%U%u"), units = "days") – Yashoda Singh Jul 15 '19 at 11:16
-
@Yashoda Singh what is `class(Customer_Retention_a$ORIGINAL_WEEK)` ? If it's of date class you don't need to add `paste` to it. You need to do it only for columns with year week format. Try doing `A <- difftime(as.Date(paste0(Customer_Retention_a$RETURNING_WEEK,1), "%Y%U%u"), Customer_Retention_a$ORIGINAL_WEEK)` also try `A <- difftime(as.Date(paste0(Customer_Retention_a$RETURNING_WEEK,1), "%Y%U%u"), as.Date(Customer_Retention_a$ORIGINAL_WEEK))` if it's of class character. – Ronak Shah Jul 15 '19 at 12:08