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.