如何在 Pandas 中格式化日期列?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/38709558/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 01:43:34  来源:igfitidea点击:

How to Format a Date Column in Pandas?

pythondatetimepandasdataframeformat

提问by MEhsan

I have a dataframe dfthat look like this:

我有一个如下所示的数据框df

   ID Date
0  1  2008-01-24 
1  2  2007-02-17

The format of Dateis %Y-%m-%d

的格式Date%Y-%m-%d

How can I format the dates to %m-%d-%Yformat?

如何格式化日期以进行%m-%d-%Y格式化?

I tried using this syntax but it did not give the right format:

我尝试使用这种语法,但它没有给出正确的格式:

df["Date"] = df["Date"].strftime("%m-%d-%Y")

Any idea how to solve this?

知道如何解决这个问题吗?

回答by root

Use the .dtaccessor:

使用.dt访问器:

df["Date"] = df["Date"].dt.strftime("%m-%d-%Y")

回答by gogognome

The accepted answer from root only works if the Datecolumn contains datetimeinstances. The dataframe shown by the original poster indicates that the Datecolumn contains dateinstances. This leads to an AttributeErrorwith the message Can only use .dt accessor with datetimelike values.

根接受的答案仅在Date列包含datetime实例时才有效。原始海报显示的数据框表明该Date列包含date实例。这导致了一个AttributeErrorwith 消息Can only use .dt accessor with datetimelike values

So you have to convert the dates to datetimes before you can format them, like this:

因此,您必须先将dates转换为s,datetime然后才能对其进行格式化,如下所示:

from datetime import datetime

df["Date"] = df["Date"].apply(lambda x: datetime.combine(x, datetime.min.time()))
df["Date"] = df["Date"].dt.strftime("%m-%d-%Y")