Home > front end >  Convert object year-week to datetime format
Convert object year-week to datetime format

Time:05-25

I have the data as below:

    New_Time    Visitors
0   2016-01 4.709530
1   2016-02 4.219508
2   2016-03 4.094345
3   2016-04 4.488636
4   2016-05 4.584967

New_time format is Year-WeekNumber, but it's currently held as dtype 'object'. I'm trying to convert New_Time from object to datetime dtype, e.g.

df_weekly_vistors_logscale['New_Time'] = df_weekly_vistors_logscale['New_Time'].dt.week

df_weekly_vistors_logscale['New_Time'] = pd.to_datetime(df_weekly_vistors_logscale['New_Time'], format = '%Y%V')

df_weekly_vistors_logscale['New_Time'] = df_weekly_vistors_logscale['New_Time'].dt.strftime('%Y-%W')

None of which are working with various errors. I'm sure the problem is logical but can't figure this one out.

Any help?

Thank you.

CodePudding user response:

Try below

import datetime
def to_datetime(x):
  return datetime.datetime.strptime(x   '-1', "%Y-%W-%w")

df_weekly_vistors_logscale['New_Time'] = df_weekly_vistors_logscale['New_Time'].apply(to_datetime)

CodePudding user response:

Try this:

import pandas as pd
df_weekly_vistors_logscale['New_Time'] = pd.to_datetime(df_weekly_vistors_logscale['New_Time'].dt.strftime('%Y-%W'))

CodePudding user response:

as an addition to the linked duplicate, if you want to convert ISO week, you can alternatively use

>>> import pandas as pd
>>> s = pd.Series(["2016-01", "2016-02", "2016-03"])
>>> pd.to_datetime(s.add("-1"), format="%G-%V-%u")
0   2016-01-04
1   2016-01-11
2   2016-01-18
dtype: datetime64[ns]
>>>
  • Related