2

Having some issues in being able to differentiate a different set of data based on dates as I'm using the .datetime(Year,Month,Day).strftime function in Python.

It seems that once it hits the 52 weeks in a year, it starts repeating it again for the next year from Week 0 which is obviously correct.

What I want to know is, is there a way of differentiating the 53rd week (the 1st week of the next year) using various functions or loops?

I'm trying to do this so that I can create a graph that extends to the present date using the weeks as the independent factor (x-axis) - currently it just extends from Week 0 to Week 52 but should realistically extend beyond that.

I've been trying to think of a logic to apply in a for loop but haven't really wrapped my head around any ideas. Any guidance would be highly appreciated as I'm fairly new to the coding scene.

Thanks!

Edit:

This is what I currently have...

for index, row in dt.iterrows():
Month = dt['Month']
Day = dt['Day']
Year = dt['Year']
date_list.append(datetime.datetime(Year[index], dt['Month'][index], dt['Day'][index]).strftime("%W"))

dt['Week'] = date_list

As my dataset goes through more than 1 years (approx 5 years currently), wouldn't I have to repeat that isocalendar code for Week 54, 55, 56 etc...

  • 3
    It's very unclear what it is you're trying to do. Can you post an [MCVE](https://stackoverflow.com/help/minimal-reproducible-example)? – Adam Smith Mar 31 '20 at 07:06
  • You could simply calculate the number of days since the first date (https://stackoverflow.com/questions/151199/how-to-calculate-number-of-days-between-two-given-dates) and then `number_of_days//7 +1` to get the week number. – Ardweaden Mar 31 '20 at 07:10

1 Answers1

1

You can use the date.isocalendar() function to go from a date to an ISO week number, or date.fromisocalendar() (new in Python 3.8) to go the other way. I found these by just opening up the documentation for the datetime module and searching for "week".

You could enumerate all the weeks in the year using these like this (again, you'll need Python 3.8 for the fromisocalendar() function):

has_week_53 = date.fromisocalendar(year, 52, 1) + timedelta(days=7) != date.fromisocalendar(year + 1, 1, 1)
week_count = 53 if has_week_53 else 52
for week in range(week_count):
    date_of_monday = date.fromisocalendar(year, week, 1)
    # use date_of_monday somehow

Edit: Here is a way of determining the week count if you cannot use Python 3.8. According to the Wikipedia article on ISO week date, the last week has the property that it always contains 28 December. So this tells you the week count:

week_count = date(year, 12, 28).isocalendar()[1]
Jim Oldfield
  • 674
  • 3
  • 8