hvnr_
hvnr_

Reputation: 15

Convert week number to week (date) with Pandas

How can I convert dt.week (which returns the week number) to show the week date? My current code:

my_net_diet_raw['Date & Time'].dt.week

Returns:

1      22
2      22
3      22
4      22
       ..
176    30
177    30
178    30
179    30
180    30
Name: Date & Time, Length: 181, dtype: int64

I would like 22 to appear as 05-25-2020, 23 to appear as 06-01-2020, etc.

Data:

0    19732166  2020-05-31  Breakfast   
1     4016406  2020-05-31  Breakfast   
2        1132  2020-05-31  Breakfast   
3    19732166  2020-05-31      Lunch   
4        1009  2020-05-31      Lunch   
..        ...         ...        ...   
176      5749  2020-07-23      Lunch   
177     20037  2020-07-23      Lunch   
178   4159294  2020-07-23      Lunch   
179  20402843  2020-07-23      Snack   
180  23053329  2020-07-23      Snack

Upvotes: 1

Views: 1036

Answers (3)

C. Dude
C. Dude

Reputation: 41

This worked for me. Is this what you are looking for?

    df['DATE']+pd.to_timedelta(6-df['DATE'].dt.weekday, unit="d")

Upvotes: 0

BOB
BOB

Reputation: 103

Assuming that y_net_diet_raw['Date & Time'].dt is a DatetimeProperties object, you should be able to use y_net_diet_raw['Date & Time'].dt.date to access the date (you don't need y_net_diet_raw['Date & Time'].dt.week). Read more at https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.dt.html and https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.dt.date.html.

If the above doesn't fit your needs, then, you might want to try this:

Converting DatetimeProperties.dt.week to DatetimeProperties.dt.date: If you wanted to get the first days of a certain number of weeks, you could do something like this (assuming that y_net_diet_raw['Date & Time'].dt.week is a Series of integers (like in your question)):

datetimes_of_first_day_of_each_week = my_net_diet_raw['Date & Time'].dt.week.apply(lambda week: datetime.strptime(f'2020 {week - 1} 1', '%Y %W %w'))

Series.apply() allows you to specify a function to compute and return a value for each given value in the original series to construct a new Series. Here, it is creating a new datetime object (for each week number) where the date is of the first day of the week (Monday, in this case), and finally returning each to create a new Series.

Upvotes: 0

BENY
BENY

Reputation: 323236

Check

pd.to_datetime(my_net_diet_raw['Date & Time']).dt.to_period('w').astype(str).str.split('/').str[0]

Upvotes: 1

Related Questions