'Pandas - Converting datetime field to a specified format

I am trying to get a date time field in Pandas in the below format

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

The above code returns date time column in the below format

2021-11-27 03:30:00

I would like to get an output of 27/11/2021 (format is dd/mm/yyyy) and the data type of the column needs to be datetime and not object.



Solution 1:[1]

If your column is a string, you will need to first use pd.to_datetime,

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

Then, use .dt datetime accessor with strftime:

df = pd.DataFrame({'Date':pd.date_range('2017-01-01', periods = 60, freq='D')})

df.Date.dt.strftime('%Y%m%d').astype(int)

Or use lambda function:

df.Date.apply(lambda x: x.strftime('%Y%m%d')).astype(int)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Gaston Alex