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 - Return the Period object as a timestamp with monthly frequency
To return the Period object as a timestamp with monthly frequency, use the period.to_timestamp() method and set the freq parameter as 'M'.
Understanding Period Objects
The pandas.Period represents a period of time. When you convert it to a timestamp with monthly frequency, it aligns to the month-end by default ?
import pandas as pd
# Creating a Period object with second frequency
period = pd.Period(freq="S", year=2021, month=9, day=18, hour=17, minute=20, second=45)
# Display the Period object
print("Period...\n", period)
# Convert to timestamp with monthly frequency
print("\nPeriod to Timestamp with monthly (month-end) frequency...\n",
period.to_timestamp(freq='M'))
Period... 2021-09-18 17:20:45 Period to Timestamp with monthly (month-end) frequency... 2021-09-30 00:00:00
Different Monthly Frequencies
You can use different monthly frequency aliases to control the alignment ?
import pandas as pd
period = pd.Period(freq="D", year=2021, month=9, day=18)
print("Original Period:", period)
# Month-end frequency
print("Month-end (M):", period.to_timestamp(freq='M'))
# Month-start frequency
print("Month-start (MS):", period.to_timestamp(freq='MS'))
Original Period: 2021-09-18 Month-end (M): 2021-09-30 00:00:00 Month-start (MS): 2021-09-01 00:00:00
Key Points
- The
to_timestamp()method converts Period objects to Timestamp objects - Using
freq='M'aligns the timestamp to month-end - Using
freq='MS'aligns the timestamp to month-start - The resulting timestamp always has time components set to 00:00:00
Conclusion
Use period.to_timestamp(freq='M') to convert Period objects to month-end timestamps. This is useful for time series analysis when you need consistent monthly alignment.
Advertisements
