Home > Blockchain >  Convert Pandas column object to date type
Convert Pandas column object to date type

Time:10-19

I have a column in my database, that represents the periods, but this column is made up of objects type data and I need to convert them to date type.

The colume looks something like this

Period
2022/07
2022/06
...
1993/02
1993/01

I don't know if the format in which they are presented could cause a problem.

CodePudding user response:

You have three options for handling errors:

errors : {'ignore', 'raise', 'coerce'}, default 'raise'
        - If :const:`'raise'`, then invalid parsing will raise an exception.
        - If :const:`'coerce'`, then invalid parsing will be set as :const:`NaT`.
        - If :const:`'ignore'`, then invalid parsing will return the input.

You can use pd.to_datetime

pd.to_datetime(df.Period, format='%Y/%m', errors="coerce").dt.date

multiple times with different formats.

CodePudding user response:

try:

df['Period'] = pd.to_datetime(df['Period'],format='%Y/%m').dt.date
  • Related