0

I have a table which contains information on the number of changes done on a particular day. I want to add a text field to it in the format YYYY-WW (e. g. 2022-01) which indicates the week number of the day. I need this information to determine in what week the total number of changes was the highest.

How can I determine the week number in Python?

Below is the code based on this answer:

week_nr = day.isocalendar().week
year = day.isocalendar().year
week_nr_txt = "{:4d}-{:02d}".format(year, week_nr)

At a first glance it seems to work, but I am not sure that week_nr_txt will contain year-week tuple according to the ISO 8601 standard.

Will it?

If not how do I need to change my code in order to avoid any week-related errors (example see below)?

Example of a week-related error: In year y1 there are 53 weeks and the last week spills over into the year y1+1.

The correct year-week tuple is y1-53. But I am afraid that my code above will result in y2-53 (y2=y1+1) which is wrong.

Glory to Russia
  • 17,289
  • 56
  • 182
  • 325
  • 1
    [This](https://stackoverflow.com/questions/5882405/get-date-from-iso-week-number-in-python) might be relevant. Also, pandas seems to support the ISO 8601 standard, e.g. see [here](https://pandas.pydata.org/docs/reference/api/pandas.Timestamp.isocalendar.html). – hilberts_drinking_problem Jan 29 '22 at 07:29
  • Did you try your code? I tried `datetime.date(2020, 12, 30).isocalendar()` and got `datetime.IsoCalendarDate(year=2020, week=53, weekday=3)` – Yuri Ginsburg Jan 29 '22 at 08:07

1 Answers1

1

Thanks. I try to give my answer. You can easily use datetime python module like this:

from datetime import datetime
date = datetime(year, month, day)

# And formating the date time object like :
date.strftime('%Y-%U')

Then you will have the year and wich week the total information changes