Reputation: 18712
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.
Upvotes: 1
Views: 1342
Reputation: 121
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
Upvotes: 1