'Pyspark : get next_day from a variable

I use deltatime to subtract 12 weeks and get the exact date but from this date I have to recover on Friday. this means that if we subtract 12 weeks I have Monday January 3, I have to make a change to get Friday January 7.

Code exemple :

I use this code to get the initial date :

week_num_period = datetime.today()- timedelta(weeks=12)
week_start_perioddddd = week_num_period.strftime("%Y-%m-%d")

but from that date i need to get the friday of that week ! i tried with

week_start_period = next_day(week_start_perioddddd, 'Friday')
week_start_period

but next_day doesn't apply on str ! could someone help me ?



Solution 1:[1]

So you want to get the formatted date for the Friday from the week 12 weeks ago? Add the timedelta of: 4 (weekday index of Friday) minus the weekday index of the day you calculated.

>>> week_num_period = datetime.today()- timedelta(weeks=12)
>>> week_num_period.date()
datetime.date(2022, 1, 6)
>>> friday = week_num_period + timedelta(days=4 - week_num_period.weekday())
>>> friday.date()
datetime.date(2022, 1, 7)
>>> week_start_period = friday.strftime("%Y-%m-%d")
>>> week_start_period
'2022-01-07'
>>>

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 jeroenflvr