How to Extract Month and Year from a Datetime Column in Pandas
We can extract the year and month from a Datetime column using pandas.Series.dt.year()
the and methods respectively. If the data is not of type, you need to convert it to first . We can also extract the year and month using the and methods .pandas.Series.dt.month()
Datetime
Datetime
pandas.DatetimeIndex.month
pandas.DatetimeIndex.year
strftime()
pandas.Series.dt.year()
and pandas.Series.dt.month()
methods to extract month and year
pandas.Series.dt.year()
The and methods applied to the Datetime type pandas.Series.dt.month()
return numpy arrays of the year and month, respectively, of the Datetime entries in the Series object.
import pandas as pd
import numpy as np
import datetime
list_of_dates = ["2019-11-20", "2020-01-02", "2020-02-05", "2020-03-10", "2020-04-16"]
employees = ["Hisila", "Shristi", "Zeppy", "Alina", "Jerry"]
df = pd.DataFrame({"Joined date": pd.to_datetime(list_of_dates)}, index=employees)
df["Year"] = df["Joined date"].dt.year
df["Month"] = df["Joined date"].dt.month
print(df)
Output:
Joined date Year Month
Hisila 2019-11-20 2019 11
Shristi 2020-01-02 2020 1
Zeppy 2020-02-05 2020 2
Alina 2020-03-10 2020 3
Jerry 2020-04-16 2020 4
However, if the column is not Datetime
of type, you should first to_datetime()
convert the column to Datetime
type using the method.
import pandas as pd
import numpy as np
import datetime
list_of_dates = ["11/20/2019", "01/02/2020", "02/05/2020", "03/10/2020", "04/16/2020"]
employees = ["Hisila", "Shristi", "Zeppy", "Alina", "Jerry"]
df = pd.DataFrame({"Joined date": pd.to_datetime(list_of_dates)}, index=employees)
df["Joined date"] = pd.to_datetime(df["Joined date"])
df["Year"] = df["Joined date"].dt.year
df["Month"] = df["Joined date"].dt.month
print(df)
Output:
Joined date Year Month
Hisila 2019-11-20 2019 11
Shristi 2020-01-02 2020 1
Zeppy 2020-02-05 2020 2
Alina 2020-03-10 2020 3
Jerry 2020-04-16 2020 4
strftime()
Method to extract year and month
strftime()
The method takes a Datetime, a format code as input, and returns a string representing the specific format specified in the output. We use %Y
and %m
as the format code to extract the year and month.
import pandas as pd
import numpy as np
import datetime
list_of_dates = ["2019-11-20", "2020-01-02", "2020-02-05", "2020-03-10", "2020-04-16"]
employees = ["Hisila", "Shristi", "Zeppy", "Alina", "Jerry"]
df = pd.DataFrame({"Joined date": pd.to_datetime(list_of_dates)}, index=employees)
df["year"] = df["Joined date"].dt.strftime("%Y")
df["month"] = df["Joined date"].dt.strftime("%m")
print(df)
Output:
Joined date year month
Hisila 2019-11-20 2019 11
Shristi 2020-01-02 2020 01
Zeppy 2020-02-05 2020 02
Alina 2020-03-10 2020 03
Jerry 2020-04-16 2020 04
pandas.DatetimeIndex.month
and pandas.DatetimeIndex.year
extract the year and month
Datetime
Another simple way to extract the month and year from a column is to retrieve the values of the year and month attributes of a pandas.DatetimeIndex object of class .
import pandas as pd
import numpy as np
import datetime
list_of_dates = ["2019-11-20", "2020-01-02", "2020-02-05", "2020-03-10", "2020-04-16"]
employees = ["Hisila", "Shristi", "Zeppy", "Alina", "Jerry"]
df = pd.DataFrame({"Joined date": pd.to_datetime(list_of_dates)}, index=employees)
df["year"] = pd.DatetimeIndex(df["Joined date"]).year
df["month"] = pd.DatetimeIndex(df["Joined date"]).month
print(df)
Output:
Joined date Year Month
Hisila 2019-11-20 2019 11
Shristi 2020-01-02 2020 1
Zeppy 2020-02-05 2020 2
Alina 2020-03-10 2020 3
Jerry 2020-04-16 2020 4
pandas.DatetimeIndex
A class is datetime64
an immutable type of data type ndarray
. It has properties like year, month, day, etc.
For reprinting, please send an email to 1244347461@qq.com for approval. After obtaining the author's consent, kindly include the source as a link.
Related Articles
Finding the installed version of Pandas
Publish Date:2025/04/12 Views:190 Category:Python
-
Pandas is one of the commonly used Python libraries for data analysis, and Pandas versions need to be updated regularly. Therefore, other Pandas requirements are incompatible. Let's look at ways to determine the Pandas version and dependenc
KeyError in Pandas
Publish Date:2025/04/12 Views:81 Category:Python
-
This tutorial explores the concept of KeyError in Pandas. What is Pandas KeyError? While working with Pandas, analysts may encounter multiple errors thrown by the code interpreter. These errors are wide ranging and can help us better invest
Grouping and Sorting in Pandas
Publish Date:2025/04/12 Views:90 Category:Python
-
This tutorial explored the concept of grouping data in a DataFrame and sorting it in Pandas. Grouping and Sorting DataFrame in Pandas As we know, Pandas is an advanced data analysis tool or package extension in Python. Most of the companies
Plotting Line Graph with Data Points in Pandas
Publish Date:2025/04/12 Views:65 Category:Python
-
Pandas is an open source data analysis library in Python. It provides many built-in methods to perform operations on numerical data. Data visualization is very popular nowadays and is used to quickly analyze data visually. We can visualize
Converting Timedelta to Int in Pandas
Publish Date:2025/04/12 Views:123 Category:Python
-
This tutorial will discuss converting a to a using dt the attribute in Pandas . timedelta int Use the Pandas dt attribute to timedelta convert int To timedelta convert to an integer value, we can use the property pandas of the library dt .
Pandas fill NaN values
Publish Date:2025/04/12 Views:93 Category:Python
-
This tutorial explains how we can use DataFrame.fillna() the method to fill NaN values with specified values. We will use the following DataFrame in this article. import numpy as np import pandas as pd roll_no = [ 501 , 502 , 503 , 50
Pandas Convert String to Number
Publish Date:2025/04/12 Views:147 Category:Python
-
This tutorial explains how to pandas.to_numeric() convert string values of a Pandas DataFrame into numeric type using the method. import pandas as pd items_df = pd . DataFrame( { "Id" : [ 302 , 504 , 708 , 103 , 343 , 565 ], "Name" :
How to Change the Data Type of a Column in Pandas
Publish Date:2025/04/12 Views:139 Category:Python
-
We will look at methods for changing the data type of columns in a Pandas Dataframe, as well as options like to_numaric , , as_type and infer_objects . We will also discuss how to to_numaric use downcasting the option in . to_numeric Method
Get the first row of Dataframe Pandas
Publish Date:2025/04/12 Views:78 Category:Python
-
This tutorial explains how to use the get_first_row pandas.DataFrame.iloc attribute and pandas.DataFrame.head() get_first_row method from a Pandas DataFrame. We will use the following DataFrame in the following example to explain how to get