0

I have a column with many dates: sample of the said list below

    Dates 
 1  2019-02-01 
 2  2018-03-10 
 3  2019-08-01 
 4  2020-02-07

I would like to have it so that if input a date, of any year I can get the week number. However, the fiscal year starts on Aug 1 of any given year. I tried just shifting the date to Jan 1 but it's different for every year due to leap years.

data['Dates'] = pd.to_datetime(data['Dates'])
data['Week'] = (data['Dates'] - timedelta(days=215)).week
print(data)

how can I get a result similar to this one below

    Dates        Week
 1  2019-02-01   27 
 2  2018-03-10   32
 3  2019-08-01   1
 4  2020-02-07   28

-Note: the weeks are probably incorrect.

2 Answers2

2

The other answer ignores the fiscal year part of the OP. I am leaving the fiscal year start date calc to the reader but this will calculate the week number (where Monday is the start of the week) from an arbitrary start date.

from dateutil import relativedelta
from datetime import date, datetime, timedelta

NEXT_MONDAY = relativedelta.relativedelta(weekday=relativedelta.MO)
LAST_MONDAY = relativedelta.relativedelta(weekday=relativedelta.MO(-1))
ONE_WEEK = timedelta(weeks=1)

def week_in_fiscal_year(d: date, fiscal_year_start: date) -> int:
    fy_week_2_monday = fiscal_year_start + NEXT_MONDAY
    if d < fy_week_2_monday:
        return 1
    else:
        cur_week_monday = d + LAST_MONDAY
        return int((cur_week_monday - fy_week_2_monday) / ONE_WEEK) + 2

adapted from this post

1

Convert it to a datetime, then call datetime.date(2010, 6, 16).strftime("%V")4

You can also use isocalendar which will return a tuple, as opposed to a string above datetime.date(2010, 6, 16).isocalendar()[1]

How to get week number in Python?

Sri
  • 2,281
  • 2
  • 17
  • 24