Pandas - Converting date column from dd/mm/yy hh:mm:ss to yyyy-mm-dd hh:mm:ss

萝らか妹 提交于 2020-05-25 07:54:06

问题


I have a dataframe (df) that has a date column (column name : sale_date) that stores data in the below format

dd/mm/yy hh:mm:ss

I am trying to convert it to yyyy-mm-dd hh:mm:ss. Tried with the below but however it still does not convert it to the required format.

df['sale_date'] = pd.to_datetime(df['sale_date'])

Could anyone assist in converting the format of this date column. Thanks


回答1:


If you know you will have a consistent format in your column, you can pass this to to_datetime:

df['sale_date'] = pd.to_datetime(df['sale_date'], format='%d/%m/%y %H:%M:%S')

If your formats aren't necessarily consistent but do have day before month in each case, it may be enough to use dayfirst=True though this is difficult to say without seeing the data:

df['sale_date'] = pd.to_datetime(df['sale_date'], dayfirst=True)



回答2:


You can do so:

df['sale_date'] = pd.to_datetime(df['sale_date'], format='%d/%m/%y %H:%M:%S').dt.strftime('%Y-%m-%d %H:%M:%S')

Input:

           sale_date
0  04/12/10 21:12:35
1  04/12/10 21:12:30

Output:

             sale_date
0  2010-12-04 21:12:35
1  2010-12-04 21:12:30


来源:https://stackoverflow.com/questions/51724883/pandas-converting-date-column-from-dd-mm-yy-hhmmss-to-yyyy-mm-dd-hhmmss

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!