Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

pandas
communitycreator

How to obtain the quarter of the year from a date in pandas

Onyejiaku Theophilus Chidalu

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 library
import pandas as pd

# creating a date time object
my_date = pd.Timestamp(2022, 4, 29)

# obtaing the quarter of the given year
print("The given date can be found in quarter ", my_date.quarter)
Implement the quarter attribute

Explanation

  • Line 4: We import the pandas library.
  • Line 7: We create a datetime object, my_date.
  • Line 10: We obtain the quarter of the year from the input datetime object using the quarter attribute.

RELATED TAGS

pandas
communitycreator

CONTRIBUTOR

Onyejiaku Theophilus Chidalu
RELATED COURSES

View all Courses

Keep Exploring