Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Python Pandas - Get day of the month that a Period falls on
To get the day of the month that a Period falls on, use the period.day property. This property extracts the day component from a Pandas Period object.
Syntax
The syntax for getting the day of the month is ?
period.day
Creating Period Objects
First, import the required libraries ?
import pandas as pd
# Creating Period objects using different methods
period1 = pd.Period("2021-09-18")
period2 = pd.Period(freq='D', year=2021, month=9, day=22, hour=4, minute=55)
print("Period1:", period1)
print("Period2:", period2)
Period1: 2021-09-18 Period2: 2021-09-22
Extracting Day of the Month
Use the .day property to extract the day component from Period objects ?
import pandas as pd
# Create Period objects
period1 = pd.Period("2021-09-18")
period2 = pd.Period(freq='D', year=2021, month=9, day=22, hour=4, minute=55)
# Get the day of the month from both Period objects
day1 = period1.day
day2 = period2.day
print("Day from Period1:", day1)
print("Day from Period2:", day2)
print("Type:", type(day1))
Day from Period1: 18 Day from Period2: 22 Type: <class 'int'>
Working with Different Frequencies
The .day property works with Period objects of different frequencies ?
import pandas as pd
# Create Period objects with different frequencies
daily = pd.Period("2021-09-15", freq='D')
monthly = pd.Period("2021-09", freq='M')
quarterly = pd.Period("2021Q3", freq='Q')
print("Daily period:", daily, "? Day:", daily.day)
print("Monthly period:", monthly, "? Day:", monthly.day)
print("Quarterly period:", quarterly, "? Day:", quarterly.day)
Daily period: 2021-09-15 ? Day: 15 Monthly period: 2021-09 ? Day: 30 Quarterly period: 2021Q3 ? Day: 30
Conclusion
The .day property provides a simple way to extract the day component from Pandas Period objects. It returns an integer representing the day of the month, regardless of the Period's frequency.
Advertisements
