Home > Software design >  How could I change all dataframe columns with "date" in the name to datetime64[ns]
How could I change all dataframe columns with "date" in the name to datetime64[ns]

Time:12-15

Just wondering if there is a shortcut, rather than iterating through the structure?

 #   Column              Non-Null Count  Dtype
---  ------              --------------  -----
 0   ID                  3 non-null      int64
 1   Name                3 non-null      object
 2   ForecastStartDate   3 non-null      object
 3   ForecastFinishDate  3 non-null      object
 4   PlannedStartDate    2 non-null      object
 5   PlannedFinishDate   3 non-null      object
 6   ActualStartDate     2 non-null      datetime64[ns]
 7   ActualFinishDate    0 non-null      datetime64[ns]

items 2 through 7 shoud ideally all be datetime64[ns]

CodePudding user response:

Below code can work, but you have to give a matching date-time format format="%Y-%m-%d %H:%M:%S.%f".

changeColumns = ['ForecastStartDate','ForecastFinishDate','PlannedStartDate','PlannedFinishDate']
df[changeColumns] = df[changeColumns].apply(pd.to_datetime, format='%Y-%m-%d %H:%M:%S.%f')
  • Related