Pandas - 将日期列从 dd/mm/yy hh:mm:ss 转换为 yyyy-mm-dd hh:mm:ss
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/51724883/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Pandas - Converting date column from dd/mm/yy hh:mm:ss to yyyy-mm-dd hh:mm:ss
提问by Kevin Nash
I have a dataframe (df) that has a date column (column name : sale_date) that stores data in the below format
我有一个数据框(df),它有一个日期列(列名:sale_date),它以以下格式存储数据
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.
我正在尝试将其转换为 yyyy-mm-dd hh:mm:ss。尝试了以下但它仍然没有将其转换为所需的格式。
df['sale_date'] = pd.to_datetime(df['sale_date'])
Could anyone assist in converting the format of this date column. Thanks
任何人都可以协助转换此日期列的格式。谢谢
回答by asongtoruin
If you know you will have a consistent format in your column, you can pass this to to_datetime
:
如果您知道您的列中将具有一致的格式,则可以将其传递给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:
如果您的格式不一定一致,但在每种情况下都有前一天,那么使用它可能就足够了,dayfirst=True
尽管在没有看到数据的情况下很难说:
df['sale_date'] = pd.to_datetime(df['sale_date'], dayfirst=True)
回答by Joe
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