My Datamframe Date columns has the datetime64[ns] type. it contains date in '%YYYY-%MM-%DD %MM:%SS:%NN. How can I change it to only show the month?
Asked
Active
Viewed 39 times
0
-
`df['Date'].dt.strftime('%m')` or `df['Date'].dt.month`? – mozway Mar 01 '23 at 13:37
1 Answers
0
Do this:
import pandas as pd
df = pd.DataFrame({'datetime_col': ['2022-01-01 12:34:56', '2022-02-01 23:45:12', '2022-03-01 03:45:56']})
df['month'] = pd.to_datetime(df['datetime_col']).dt.strftime('%m')
print(df)
which is
datetime_col month
0 2022-01-01 12:34:56 01
1 2022-02-01 23:45:12 02
2 2022-03-01 03:45:56 03

Serge de Gosson de Varennes
- 7,162
- 3
- 18
- 39