How to obtain the quarter of the year from a date in pandas
Overview
The quarter attribute returns the quarter of the year for any given Timestamp object (an equivalent of Python's datetime object).
For a given year, there are four (4) quarters. The quarter attribute will return 1 if the given date can be found in the first quarter. It returns 2 if the given date can be found in the second quarter, and so on.
Syntax
The quarter attribute takes the following syntax:
Timestamp.quarter
The syntax for the quarter attribute
Parameter value
Since it is an attribute, quarter takes no parameter value.
Return value
The quarter attribute returns an int from 1 to 4 representing the quarter for which the input date time object can be found.
Example
# A code to illustrate the quarter attribute in Pandas# importing the pandas libraryimport pandas as pd# creating a date time objectmy_date = pd.Timestamp(2022, 4, 29)# obtaing the quarter of the given yearprint("The given date can be found in quarter ", my_date.quarter)
Explanation
- Line 4: We import the
pandaslibrary. - Line 7: We create a
datetimeobject,my_date. - Line 10: We obtain the quarter of the year from the input
datetimeobject using thequarterattribute.