1

I have a dataframe column with datetime data in 1980-12-11T00:00:00 format.

I need to convert the whole column to DD/MM/YYY string format.

Is there any easy code for this?

Bimons
  • 221
  • 2
  • 13
  • 1
    https://stackoverflow.com/questions/30132282/datetime-to-string-with-series-in-python-pandas So something like dates.strftime('%d-%m-%Y') – bbd108 Feb 01 '19 at 04:17
  • `pd.to_datetime('1980-12-11T00:00:00').strftime('%d/%m/%Y')` : `'11/12/1980'` – anky Feb 01 '19 at 04:26

3 Answers3

1

Creating a working example:

df = pd.DataFrame({'date':['1980-12-11T00:00:00', '1990-12-11T00:00:00', '2000-12-11T00:00:00']})
print(df)

                  date
0  1980-12-11T00:00:00
1  1990-12-11T00:00:00
2  2000-12-11T00:00:00

Convert the column to datetime by pd.to_datetime() and invoke strftime()

df['date_new']=pd.to_datetime(df.date).dt.strftime('%d/%m/%Y')
print(df)

                  date    date_new
0  1980-12-11T00:00:00  11/12/1980
1  1990-12-11T00:00:00  11/12/1990
2  2000-12-11T00:00:00  11/12/2000
anky
  • 74,114
  • 11
  • 41
  • 70
  • I am getting: OutOfBoundsDatetime: Out of bounds nanosecond timestamp: 7020-11-11 00:00:00 – Bimons Feb 01 '19 at 05:02
  • No, definitely not the year. The format of the date before converting to string is YYYY-MM-DDT00:00:00 – Bimons Feb 01 '19 at 05:05
  • exactly ` 7020-11-11 00:00:00` this line is where the error is occurring. :) since pandas cant 7020 as year – anky Feb 01 '19 at 05:07
  • ah, its a problem with the data! Is there any way to not stop on errors like that? – Bimons Feb 01 '19 at 05:07
  • @Bimons you can check this and other related links. :) https://stackoverflow.com/questions/32888124/pandas-out-of-bounds-nanosecond-timestamp-after-offset-rollforward-plus-adding-a – anky Feb 01 '19 at 05:11
1

You can use pd.to_datetime to convert string to datetime data

pd.to_datetime(df['col'])

You can also pass specific format as:

pd.to_datetime(df['col']).dt.strftime('%d/%m/%Y')
anshukira
  • 81
  • 1
  • 4
0

When using pandas, try pandas.to_datetime:

import pandas as pd
df = pd.DataFrame({'date': ['1980-12-%sT00:00:00'%i for i in range(10,20)]})
df.date = pd.to_datetime(df.date).dt.strftime("%d/%m/%Y")
print(df)
         date
0  10/12/1980
1  11/12/1980
2  12/12/1980
3  13/12/1980
4  14/12/1980
5  15/12/1980
6  16/12/1980
7  17/12/1980
8  18/12/1980
9  19/12/1980
Chris
  • 29,127
  • 3
  • 28
  • 51