2

I have a date column in a dataframe in the format yyyy/mm/dd like this:

Date
2016/08/22
2016/08/10
2016/08/08
...

How do I convert it into dd/mm/yyyyformat??

Shubham R
  • 7,382
  • 18
  • 53
  • 119
user517696
  • 2,472
  • 7
  • 24
  • 35

3 Answers3

5

I assume the column is in string.

import pandas as pd

df = (pd.DataFrame([['2016/08/22']*10]*10))

df[0] = pd.to_datetime(df[0]).apply(lambda x:x.strftime('%d/%m/%Y'))

output:

enter image description here

Alex Fung
  • 1,996
  • 13
  • 21
2

Use a vectorized approached with the dt accessor in combination with strftime

df = pd.DataFrame(dict(date=['2011/11/30', '2012/03/15']))
df['date'] = pd.to_datetime(df.date).dt.strftime('%d/%m/%Y')

print(df)

         date
0  30/11/2011
1  15/03/2012
piRSquared
  • 285,575
  • 57
  • 475
  • 624
  • Side-note, I think that's **the** thing in pandas to know about, notice `df['date']` for the column being changed but the easier `df.date` when just being read from, I learned that pro tip the hard way, unless I'm mistaken – gseattle May 12 '22 at 09:01
  • Pandas will check its columns and add a convenience attribute matching the column name so long as the name satisfies python's requirements for attribute names. If that column and attribute already exist, you can very well assign to the column with `df.date = somestuff`. If that attribute does note exist yet then doing `df.date = somestuff` just stuffs `somestuff` into an attribute of the dataframe instance. And that will likely get clobbered with the next method you use on that instance. – piRSquared May 13 '22 at 18:10
2

Suppose your dataframe df has date column 'date', then you can use this method, to change your date format.

df['date'] = df['date'].dt.strftime('%m/%d/%Y')
Shubham R
  • 7,382
  • 18
  • 53
  • 119