converting a pandas date to week number
Just access the dt
week attribute:
In [286]:
df['Date'].dt.week
Out[286]:
0 25
dtype: int64
In [287]:
df['Week_Number'] = df['Date'].dt.week
df
Out[287]:
Date Week_Number
0 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 pd
df['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)
from datetime import date
df_date = pd.DataFrame([date.today()],columns = ['today'])
print(df_date)
#### Print Output ####
# today
#0 2019-09-07
df_date['weeknum'] = df_date.today.apply(lambda x:x.isocalendar()[1])
print(df_date)
#### Print Output ####
# today weeknum
#0 2019-09-07 36