0

I have a df_mixed column containing data in yyyyww format, eg: 201501, 201502…etc I have to extract the last date of the week and put it in ds column.

For eg: For 201501, last day of week 1 is 4-1-2015 For 201502, last day is 11-1-2015

I have to follow the ISO format. According to the ISO format the 1st week of 2015 starts from 29th December 2014 and ends on 4th January 2015

Any idea how to go about it using python, pandas and datetime library?

molbdnilo
  • 64,751
  • 3
  • 43
  • 82
smrithi
  • 67
  • 8
  • Do you require the last day of all weeks in the particular month or is there a criteria? – Vidya Ganesh Aug 05 '21 at 17:47
  • duplicate of [Get first and last day of given week number in python](https://stackoverflow.com/a/51194746/10513549) – JWB Aug 05 '21 at 17:48
  • 1
    Does this answer your question? [Get first and last day of given week number in python](https://stackoverflow.com/questions/51194745/get-first-and-last-day-of-given-week-number-in-python) – JWB Aug 05 '21 at 17:48
  • I think the question is `Pandas` specific and thus not that duplicate – Prayson W. Daniel Aug 05 '21 at 17:50
  • @VidyaGanesh Yes I need the last days for all the weeks given in the dataset i.e. from 201501 to 201805. – smrithi Aug 05 '21 at 18:43
  • Please read the [description](https://stackoverflow.com/tags/ml/info) of the ML tag. – molbdnilo Aug 05 '21 at 19:10

2 Answers2

1

IIUC use pd.to_datetime to construct the datetime in format %Y%W%w. I added 0 as the weekday since you want Sundays which is first day of a week:

df = pd.DataFrame({"Date":[201501, 201502]})

df["Date"] = pd.to_datetime((df["Date"]-1).astype(str)+"0", format="%Y%W%w")

print (df)

        Date
0 2015-01-04
1 2015-01-11
Henry Yik
  • 22,275
  • 4
  • 18
  • 40
0

Assuming this input:

df = pd.DataFrame({'date': ['201501', '201502']})

If you choose Sunday as the last day of week:

df['date2'] = pd.to_datetime(df['date']+'Sun', format='%Y%W%a')
df

output:

     date      date2
0  201501 2015-01-11
1  201502 2015-01-18

NB. if you want American week format, use %U in place of %W and Mon as the last day of week. See the doc for datetime for more precisions

mozway
  • 194,879
  • 13
  • 39
  • 75