如何在 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
How to Format a Date Column in Pandas?
提问by MEhsan
I have a dataframe df
that look like this:
我有一个如下所示的数据框df
:
ID Date
0 1 2008-01-24
1 2 2007-02-17
The format of Date
is %Y-%m-%d
的格式Date
是%Y-%m-%d
How can I format the dates to %m-%d-%Y
format?
如何格式化日期以进行%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 gogognome
The accepted answer from root only works if the Date
column contains datetime
instances. The dataframe shown by the original poster indicates that the Date
column contains date
instances. This leads to an AttributeError
with the message Can only use .dt accessor with datetimelike values
.
根接受的答案仅在Date
列包含datetime
实例时才有效。原始海报显示的数据框表明该Date
列包含date
实例。这导致了一个AttributeError
with 消息Can only use .dt accessor with datetimelike values
。
So you have to convert the date
s to datetime
s before you can format them, like this:
因此,您必须先将date
s转换为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")