1

I would like to extract a week number from a data in panda dataframe but starting from the SPECIFIC date.

For example from 4th April:

20/04/2010 --> 1

27/04/2010 --> 2

04/05/2010 --> 3

and so on..

Any idea?

Thank you in advance!

Chiheb Nexus
  • 9,104
  • 4
  • 30
  • 43
Sheron
  • 585
  • 2
  • 9
  • 24

2 Answers2

2

Just calculate the difference in days between 2 dates, divide by 7 and add 1 :

from datetime import date

origin = date(2010, 4, 20)

def week_number_from(my_date, origin):
    return (my_date - origin).days / 7 + 1
Eric Duminil
  • 52,989
  • 9
  • 71
  • 124
  • @Giada if this answers your question, consider upvoting the answer and selecting it as your chosen answer by clicking the green check. – piRSquared Mar 07 '17 at 07:19
1

Use pandas to_datetime to parse your date column if it is not already in datetime format.

http://pandas.pydata.org/pandas-docs/stable/generated/pandas.to_datetime.html

Then use the date time method weekday.

https://docs.python.org/2/library/datetime.html

my_dataframe['week_nums'] = pandas.to_datetime(my_dataframe['date_col']).weekday()

Sorry I saw you want week day from specific date, will update answer... it is easy to calculate the difference between 2 dates.

jeffery_the_wind
  • 17,048
  • 34
  • 98
  • 160