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 yearly frequency
To return the Period object as a timestamp with yearly frequency, use the period.to_timestamp() method and set the freq parameter as 'Y'.
What is a Pandas Period?
The pandas.Period represents a period of time with a specific frequency. It can represent time spans like seconds, minutes, hours, days, months, or years ?
Creating a Period Object
First, let's create a Period object with second-level frequency ?
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)
print("Period...")
print(period)
Period... 2021-09-18 17:20:45
Converting to Timestamp with Yearly Frequency
The to_timestamp() method converts a Period to a Timestamp. When we set freq='Y', it returns the year-end timestamp ?
import pandas as pd
# Creating a Period object
period = pd.Period(freq="S", year=2021, month=9, day=18, hour=17, minute=20, second=45)
print("Original Period:")
print(period)
# Convert to timestamp with yearly frequency (year-end)
yearly_timestamp = period.to_timestamp(freq='Y')
print("\nPeriod to Timestamp with yearly frequency:")
print(yearly_timestamp)
Original Period: 2021-09-18 17:20:45 Period to Timestamp with yearly frequency: 2021-12-31 00:00:00
Different Yearly Frequency Options
You can also use year-start frequency with 'YS' ?
import pandas as pd
period = pd.Period(freq="S", year=2021, month=9, day=18, hour=17, minute=20, second=45)
print("Year-end frequency (Y):")
print(period.to_timestamp(freq='Y'))
print("\nYear-start frequency (YS):")
print(period.to_timestamp(freq='YS'))
Year-end frequency (Y): 2021-12-31 00:00:00 Year-start frequency (YS): 2021-01-01 00:00:00
Conclusion
Use period.to_timestamp(freq='Y') to convert a Period to a year-end timestamp. Use freq='YS' for year-start timestamps. This is useful for aggregating data by yearly periods.
Advertisements
