Convert DataFrame column type from string to datetime, dd/mm/yyyy format

后端 未结 4 872
花落未央
花落未央 2020-11-22 10:13

How can I convert a DataFrame column of strings (in dd/mm/yyyy format) to datetimes?

4条回答
  •  無奈伤痛
    2020-11-22 10:50

    If you have a mixture of formats in your date, don't forget to set infer_datetime_format=True to make life easier

    df['date'] = pd.to_datetime(df['date'], infer_datetime_format=True)

    Source: pd.to_datetime

    or if you want a customized approach:

    def autoconvert_datetime(value):
        formats = ['%m/%d/%Y', '%m-%d-%y']  # formats to try
        result_format = '%d-%m-%Y'  # output format
        for dt_format in formats:
            try:
                dt_obj = datetime.strptime(value, dt_format)
                return dt_obj.strftime(result_format)
            except Exception as e:  # throws exception when format doesn't match
                pass
        return value  # let it be if it doesn't match
    
    df['date'] = df['date'].apply(autoconvert_datetime)
    

提交回复
热议问题