0

In my recent work with pandas, I encountered a challenge related to formatting datetime values. Unfortunately, whenever I attempt to change the datetime column's format to "DD-MM-YYYY" it results in the dtype being converted to an object, which is not desirable.

import pandas as pd

data = {
    'id': [1, 2, 3],
    '_time': ["2023-07-27 10:30:00", "2023-07-28 15:45:00", "2023-07-29 09:15:00"]
}
df = pd.DataFrame(data)

df['_time'] = pd.to_datetime(df['_time'])

df['_time'] = df['_time'].dt.strftime("%d-%m-%Y %H:%M:%S")

print(df) 

print(df.dtypes)
  • The code above successfully formats the data as desired, but it alters the dtype of the "_time" column to an object type.

including trying various methods using pandas and the datetime module, I haven't been able to find a solution to preserve the desired dtype (datetime64). The issue persists, and I'm still searching for a resolution.

FObersteiner
  • 22,500
  • 8
  • 42
  • 72
Bennison J
  • 414
  • 1
  • 12
  • 1
    Does this answer your question? [How to change the datetime format in Pandas](https://stackoverflow.com/questions/38067704/how-to-change-the-datetime-format-in-pandas) – PV8 Jul 27 '23 at 11:00
  • this question will help: https://stackoverflow.com/questions/38067704/how-to-change-the-datetime-format-in-pandas – PV8 Jul 27 '23 at 11:01
  • Just to help you understand what's happening....when you run this line: df['_time'] = df['_time'].dt.strftime("%d-%m-%Y %H:%M:%S") ...the strftime() function transforms a datetime to a string in the specified string format. So it's overwriting your datetime column with string. The answers linked above should be helpful in figuring out what you're looking to do. – markd227 Jul 27 '23 at 18:06
  • 1
    to complement @markd227 's comment: if you have datetime represented as a string, it has a certain format. If however you have datetime data type, it doen't have a format. So, you can change the format in a string, but not in datetime dtype. What you see if you print the column is just its string *representation*. – FObersteiner Jul 27 '23 at 18:16

0 Answers0