How to convert datetime in pandas to week date?

Question:

I have a dataframe with datetimes but would like to convert it to week dates. These week conversion should align with the pd.grouper(freq='W') format. How can I do this?

date         | week_date
2022-03-10   | 2022-03-06
2022-03-15   | 2022-03-13
2022-03-21   | 2022-03-20

When you use pd.grouper(freq=’W’), these results of how weeks are formatted is in the week_date column above. How do I get this formatting without using grouper just by a random date of a user?

Asked By: titutubs

||

Answers:

Does this get at what you’re looking for?

import pandas as pd

# Make frame
data = {"date": ["2022-03-10", "2022-03-15", "2022-03-21"]}
df = pd.DataFrame(data=data)

# Convert values to datetime
df["date"] = pd.to_datetime(df["date"])

# Get week number, with pd.DateOffset used to start the week on Sunday
week_date_values = df["date"].dt.isocalendar()
df["week_date"] = (df['date'] - pd.to_timedelta(df['date'].dt.dayofweek, unit='d') + pd.DateOffset(days=-1)).dt.strftime("%Y-%m-%d")

# Combine with "(week n)" values
df["week_date"] = df["week_date"] + " " + "(week " + week_date_values["week"].astype(str) + ")"

Output

date week_date
2022-03-10 2022-03-06 (week 10)
2022-03-15 2022-03-13 (week 11)
2022-03-21 2022-03-20 (week 12)
Answered By: Ray
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.