get a month from a date column in python

To get a month from a date column in pandas, we can first convert the string date column to a datetime object using the to_datetime function from the pandas library. Then, we can use the dt.month attribute to extract the month from the datetime object.

Here's an example code block:

main.py
import pandas as pd

# create a sample dataframe with a date column
df = pd.DataFrame({'date_column': ['2022-01-01', '2022-02-01', '2022-03-01']})

# convert the date column to datetime object
df['date_column'] = pd.to_datetime(df['date_column'])

# extract month from the datetime object
df['month'] = df['date_column'].dt.month

print(df)
341 chars
13 lines

Output:

main.py
  date_column  month
0  2022-01-01      1
1  2022-02-01      2
2  2022-03-01      3
84 chars
5 lines

gistlibby LogSnag