0

I wan't to change the format of a date column in pandas. In my example called df_transactions['date'].

The format I am aiming for is format='%d-%m-%Y'. However my code, doesn't seem to work.

This is the code I tried:

df_transactions['date'] = pd.to_datetime(df_transactions['date'], format='%d-%m-%Y')

Not sure if it's important information but I did a check on the datatype and it says: dtype: datetime64[ns, pytz.FixedOffset(60)

Any help is much appreciated.

YellowSkin
  • 25
  • 5
  • What is the problem with the code? to_datetime transforms into a datetime – Dani Mesejo Dec 20 '20 at 14:12
  • [pd.to_datetime](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.to_datetime.html) returns a datetimeindex, whereas a formated date is a string. The 'format' argument of to_datetime helps you parse datetime from a string. If you want to get a string at the end, you should use [df_transactions.dt.strftime](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.dt.strftime.html) (after converting using to_datetime) – tgrandje Dec 20 '20 at 14:14

2 Answers2

1

You need to do something like this:

import pandas as pd

# dummy data (assuming the date column is a string)
rng = pd.date_range(pd.Timestamp("2018-03-10 09:00"), periods=3, freq='s')
df_transactions = pd.DataFrame()
df_transactions['date'] = rng.astype('string')


# transform to datetime and format with strftime
df_transactions['date'] = pd.to_datetime(df_transactions['date']).dt.strftime('%d-%m-%Y')
print(df_transactions)

Output

         date
0  10-03-2018
1  10-03-2018
2  10-03-2018

See the documentation on strftime for more information. Note that if the column is already a something like a DatetimeIndex, you don't need to use to_datetime.

Dani Mesejo
  • 61,499
  • 6
  • 49
  • 76
0

I think you should try:

df_transactions['date'] = pd.to_datetime(df_transactions['date'])

and then do this:

df_transactions['date'] = pd.to_datetime(df_transactions['date'].dt.strftime(format='%d-%m-%Y'))