问题
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