pandas 将数据框日期列的 dd-mm-yyyy 日期格式更改为 yyyy-mm-dd
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/51822956/
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
Change dd-mm-yyyy date format of dataframe date column to yyyy-mm-dd
提问by user1315789
I have this panda dataframe df
.
我有这个Pandas数据框df
。
Name Date Score Score2
Joe 26-12-2007 53.45 53.4500
Joe 27-12-2007 52.38 52.7399
Joe 28-12-2007 51.71 51.8500
I would like to convert the date format in the Date
column from dd-mm-yyyy
to yyyy-mm-dd
. The converted dataframe will look like this;
我想将Date
列中的日期格式从转换dd-mm-yyyy
为yyyy-mm-dd
. 转换后的数据框将如下所示;
Name Date Score Score2
Joe 2007-12-26 53.45 53.4500
Joe 2007-12-27 52.38 52.7399
Joe 2007-12-28 51.71 51.8500
I am using python v3.6
我正在使用 python v3.6
A question marked as duplicate assumes that the original date format is yyyy-mm-dd
. However, the original date format in this question is dd-mm-yyyy
. If I were to apply the answer in that question, the converted dates is wrong.
How to change the datetime format in pandas
标记为重复的问题假定原始日期格式为yyyy-mm-dd
. 但是,此问题中的原始日期格式是dd-mm-yyyy
. 如果我要应用该问题的答案,则转换后的日期是错误的。
如何更改Pandas中的日期时间格式
回答by Rakesh
Use '%Y-%m-%d'
用 '%Y-%m-%d'
Ex:
前任:
import pandas as pd
df = pd.DataFrame({"Date": ["26-12-2007", "27-12-2007", "28-12-2007"]})
df["Date"] = pd.to_datetime(df["Date"]).dt.strftime('%Y-%m-%d')
print(df)
Output:
输出:
Date
0 2007-12-26
1 2007-12-27
2 2007-12-28