pandas -将日期列从dd/mm/yy hh:mm:ss转换为yyyy-mm-dd hh:mm:ss [英] Pandas - Converting date column from dd/mm/yy hh:mm:ss to yyyy-mm-dd hh:mm:ss
问题描述
我有一个数据框(df),该数据框具有一个日期列(列名:sale_date),该列以以下格式存储数据
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
我正在尝试将其转换为yyyy-mm-dd 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
推荐答案
如果您知道自己的列将具有一致的格式,则可以将其传递给to_datetime
:
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')
如果您的格式不一定一致,但在每种情况下确实都有前一天,那么使用dayfirst=True
可能就足够了,尽管在不查看数据的情况下很难说:
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)
这篇关于 pandas -将日期列从dd/mm/yy hh:mm:ss转换为yyyy-mm-dd hh:mm:ss的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!