0

I am getting a list of dates in the format

Date
20180223
20180120
20180201 

I want to get the week numbers for these in a new column

Date        Week_num 
20180223       8 
20180120       3 
20180210       6

The code being used to get the date here is :

yyyymmdd= (dt.datetime.today()-timedelta(days=1)+timedelta(hours=5.3)).strftime('%Y%m%d')

I need help with getting the weeks for the same.

ShivaGaire
  • 2,283
  • 1
  • 20
  • 31
Var0115
  • 21
  • 7
  • 1
    Possible duplicate of [How to get week number in Python?](https://stackoverflow.com/questions/2600775/how-to-get-week-number-in-python) – Kraay89 Mar 05 '18 at 11:26
  • I am able get it for a fixed date or sysdate. But here I have different dates in a different pattern . – Var0115 Mar 05 '18 at 11:31

2 Answers2

0

You'll have to convert your date back to a datetime.date() object:

>>> mydate = datetime.datetime.strptime("20180223", "%Y%m%d").date()
>>> mydate
datetime.date(2018, 2, 23)

datetime.date() has a date.isocalendar(), which contains ISO year, ISO week number and ISO weekday:

>>> mydate.isocalendar()
(2018, 8, 5)

As you can see the second entry to the tuple is the weeknumber you are looking for.

>>> mydate.isocalendar()[1]
8
Kraay89
  • 919
  • 1
  • 7
  • 19
  • This works fine for one date i.e. 20180223 but I require a solution such that I get a conversion for df["Date"] as a whole for the entire column – Var0115 Mar 05 '18 at 11:52
  • That is a whole different question and was never stated in the original question. I suggest that you accept this answer, as it does exactly what you asked, and go try to find the answer to your next question for yourself first. – Kraay89 Mar 05 '18 at 11:59
  • Also, you can feed the entries in your df['date'] into this answer one by one, by a loop of some sorts. – Kraay89 Mar 05 '18 at 12:01
0

You can create a new week column using .apply() and lambda to impact all values in a column.

df['week'] = df['existing_date_col'].apply(lambda x: x.isocalendar()[1])