0

I ran into something peculiar. I wanted to extract week numbers from dates.

Look what happend with the january 1st:

strftime(as.Date("2021-01-01"), format = "%Y-%V")
[1] "2021-53"

Obviously this not right. What happens here and how can I prevent this from happening?

zx8754
  • 52,746
  • 12
  • 114
  • 209
rdatasculptor
  • 8,112
  • 14
  • 56
  • 81
  • 4
    See e.g. [this answer](https://stackoverflow.com/questions/45549449/transform-year-week-to-date-object/45587644#45587644) for different definitions of week. – Henrik Mar 15 '21 at 20:25
  • How are you defining week number? When does the week number increase? Is it every seven days? Every sunday? Is it OK if the first week doesn't have 7 days? – MrFlick Mar 15 '21 at 20:25
  • @MrFlick yes it is okay the first week doesn't have 7 days, and I start the week on monday. – rdatasculptor Mar 15 '21 at 20:36

1 Answers1

4

53 is correct because 2021-01-01 is in the 53rd week of 2020 by the ISO week date system. Week 53 runs from 2020-12-28 through 2021-01-03, inclusive.

2021 is incorrect. It is not the 53rd week of 2021, but rather the 53rd week of 2020.

The problem is that you are using %Y for the year. When combined with the week number, you should instead be using %G for the year. See the docs here.

Also, the ISO 8601 standard requires a W before the week number to be fully compliant. Change your format to "%G-W%V" and it will correctly produce "2020-W53"

Matt Johnson-Pint
  • 230,703
  • 74
  • 448
  • 575