将数据框日期列的dd-mm-yyyy日期格式更改为yyyy-mm-dd [英] Change dd-mm-yyyy date format of dataframe date column to yyyy-mm-dd
本文介绍了将数据框日期列的dd-mm-yyyy日期格式更改为yyyy-mm-dd的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有这个熊猫数据框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
我想将Date
列中的日期格式从dd-mm-yyyy
转换为yyyy-mm-dd
.转换后的数据帧将如下所示;
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;
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
我正在使用python v3.6
I am using python v3.6
标记为重复的问题假定原始日期格式为yyyy-mm-dd
.但是,此问题中的原始日期格式为dd-mm-yyyy
.如果我要在该问题中使用答案,则转换后的日期是错误的.
如何在熊猫中更改日期时间格式
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
推荐答案
使用'%Y-%m-%d'
例如:
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)
输出:
Date
0 2007-12-26
1 2007-12-27
2 2007-12-28
这篇关于将数据框日期列的dd-mm-yyyy日期格式更改为yyyy-mm-dd的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文