How to Format a Date Column in Pandas?

狂风中的少年 提交于 2020-04-14 08:08:47

问题


I have a dataframe df that look like this:

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

The format of Date is %Y-%m-%d

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

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?


回答1:


Use the .dt accessor:

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



回答2:


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.

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

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")


来源:https://stackoverflow.com/questions/38709558/how-to-format-a-date-column-in-pandas

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!