Home > front end >  Convert WW-YYYY Object to datetime format
Convert WW-YYYY Object to datetime format

Time:09-24

I have the following data which has been scraped from a website and I need to convert it into its respective datetime format. Here is the first 5 rows in the column df['Date'].

df['Date'] first 5 rows

Currently the dtype of df['Data'] is an Object, but I would like to convert it to being datetime WWYYYY so that I can use it for time series plotting.

When I try the following code, I get the error below.

df["Date"] = pd.to_datetime(df["Date"],format='%W-%Y')

ValueError: Cannot use '%W' or '%U' without day and year

Obviously my starting data does not have the days so this is a bit of a problem. I have no need to present the data in a daily output, so is there a way to introduce an arbitrary day on every date or alternatively (preferred option) to convert to datetime format without a day?

CodePudding user response:

As the error says, for week number, a day is required as it does not know which of the 7 days it needs to convert the week-year to. While you may not need, the datetime expects the day to be specified. So, you can add -1 to the string (for first day of the week) before converting it and use %w (for day of week) in the format. Example below..

df['Date'] = df['Date']   "-1"
df["Date"] = pd.to_datetime(df["Date"],format='%U-%Y-%w')
df.info()
 #   Column  Non-Null Count  Dtype         
---  ------  --------------  -----         
 0   Date    5 non-null      datetime64[ns]
  • Related