How to Format a Date Column in Pandas?

13,444

Solution 1

Use the .dt accessor:

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

Solution 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")
Share:
13,444
MEhsan
Author by

MEhsan

Updated on July 26, 2022

Comments

  • MEhsan
    MEhsan almost 2 years

    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?