converting a pandas date to week number
Just access the dt
week attribute:
In [286]:df['Date'].dt.weekOut[286]:0 25dtype: int64In [287]:df['Week_Number'] = df['Date'].dt.weekdfOut[287]: Date Week_Number0 2015-06-17 25
Here is another possibility using strftime
. strftime.org
is a good resource.
df['Week_Number'] = df['Date'].dt.strftime('%U')
'%U'
represents the week number of the year (Sunday as the first day of the week) as a zero padded decimal number. All days in a new year preceding the first Sunday are considered to be in week 0.
If you have dates from multiple years, I recommend creating a Year-Week combination
df['Year-Week'] = df['Date'].dt.strftime('%Y-%U')
Pandas has its .dayofyear
and .weekofyear
functionality, which can be applied straight away to the output of pandas.to_datetime(df['column_name'])
, giving type "Timestamp" as the output.
import pandas as pddf['formatted_date'] = pd.to_datetime(df['datetime'])df['day_of_year'] = df.formatted_date.apply(lambda x: x.dayofyear)df['week_of_year'] = df.formatted_date.apply(lambda x: x.weekofyear)