Python get month from date
Learn how to simply get the month number from a date or datetime object in Python
1. Get month from date
2. Get month from date in Pandas
3. Get year month from date
4. Get year month from date in Pandas
Being able to get the month number, or year month number, from a DateTime object in Python can be extremely helpful for feature engineering. In this post, I will walk through how to do this simply in multiple variations.
How do you get the month number from a datetime object in Python?
In order to get the month number from a datetime object in Python, all you need to do is use the .month
method. This is a much simpler operation than getting, for example, the week number as there arenโt multiple interpretations of the aggregation.
Python get month from date
Getting the month number from a datetime object in Python requires very little code, here is the most simple example of implementing it.
import datetime
date = datetime.date(2022, 9, 1)
month_number = date.month
print(date)
print(f"Month number is: {month_number}")
"""
Output:
2022-09-01
Month number is: 9
"""
Pandas get month number from datetime
If youโre using Pandas as a way to store your data then you can easily get the month number from a datetime column by using the .dt.month
method.
import pandas as pd
df = pd.DataFrame(
columns=["datetime"],
data=pd.date_range("30/8/2022 09:00:00", periods=4, freq="D"))
df["month_number"] = df["datetime"].dt.month
"""
Output:
datetime month_number
0 2022-08-30 09:00:00 8
1 2022-08-31 09:00:00 8
2 2022-09-01 09:00:00 9
3 2022-09-02 09:00:00 9
"""
Python get year month number from date
If you have a dataset that spans multiple years then you may want to return a combination of year and month to make it unique. Here is how this can be done in Python using strftime
import datetime
date = datetime.date(2022, 9, 1)
year_month = date.strftime('%Y-%m')
print(date)
print(f"Year month combination: {year_month}")
"""
Output:
2022-09-01
Year month combination: 2022-09
"""
Pandas get year month number from datetime
Itโs also possible to calculate this unique year-month combination for a Pandas dataframe using the same approach.
import pandas as pd
df = pd.DataFrame(
columns=["datetime"],
data=pd.date_range("30/8/2022 09:00:00", periods=4, freq="D"))
df["year_month"] = df["datetime"].dt.strftime('%Y-%m')
"""
Output:
datetime year_month
0 2022-08-30 09:00:00 2022-08
1 2022-08-31 09:00:00 2022-08
2 2022-09-01 09:00:00 2022-09
3 2022-09-02 09:00:00 2022-09
"""
Related articles
Python round DateTime to day
Python round DateTime to week
Python round DateTime to start or end of month
Python get week number from DateTime
Python convert datetime64 to date
Python get year from DateTime